鼠标移动到up盒子上,图片pic向上滑动,在图片还未滑动到指定位置时,再次触发onmouseover事件。
以下采用setInterval()的方法写的定时器,下一次触发onmouseover事件时,可以清除上次未执行完的动作。
<script type="text/javascript">
window.onload = function(){
var up = document.getElementById("up");
var pic =document.getElementById("pic");
var num = 0;
var speed = 20;
var timer = null;
up.onmouseover = function() {
clearInterval(timer);
timer = setInterval(fnUp,speed);
function fnUp(){
num--;
if(num >= -1070){
pic.style.top = num + "px";
} else {
clearInterval(timer);
}
};
};
</script>但以下采用setTimeout()方法写的定时器,在下一次触发onmouseover事件时,无法清除上次未执行完的动作。
<script type="text/javascript">
window.onload = function(){
var up = document.getElementById("up");
var pic =document.getElementById("pic");
var num = 0;
var speed = 20;
var timer = null;
up.onmouseover = function(){
clearTimeout(timer);
setTimeout(fnUp,speed);
function fnUp(){
num = num -1;
if(num > -1070){
pic.style.top = num + "px";
setTimeout(fnUp,speed);
}
}
}
}
</script>