DOM基本操作:
window上有三个方法
scroll(),scrollTo(), scrollBy();
三个方法功能类似,用法都是将x,y坐标传入。即实现让滚动轮滚动到当前位置。
区别:scrollBy()会在之前的数据基础之上做累加。
eg:利用scrollBy()快速阅读的功能。
<div style="width: 100px;height: 100px;background-color: orange;
color: #fff;font-size: 40px;font-weight:bold; text-align: center;line-height: 100px;
position: fixed;bottom: 200px;right: 50px;border-radius: 50%;opacity: 0.5;">start</div>
<div style="width: 100px;height: 100px;background-color: #0f0;
color: #fff;font-size: 40px;font-weight:bold; text-align: center;line-height: 100px;
position: fixed;bottom: 50px;right: 50px;border-radius: 50%;opacity: 0.5;">stop</div>
<script>
var start = document.getElementsByTagName('div')[0];
var stop = document.getElementsByTagName('div')[1];
var timer = 0;
var key = true;
start.onclick = function() {
if (key) {
timer = setInterval(function() {
window.scrollBy(0, 10);
}, 100)
key = false;
}
}
stop.onclick = function() {
clearInterval(timer);
key = true;
}
</script>
在写这个程序时如果不断点击start的话会导致页面滚动速度不断加速,就算点击stop也只能清除他所对应的那其中一个timer,因此利用加锁思想,给程序增加一个变量key,当程序还没触发执行时key的值为true,当触发start事件时让key的值为false,使程序无论怎么点击都不再加速,当触发了stop事件时将key赋值为true