<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>缓冲动画</title>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
<style>
*{
margin:0;
padding:0;
}
#wrap{
width:100px;
height:100px;
background:red;
position:relative;
left:-100px;
}
#share{
width:20px;
height:30px;
background:blue;
position:absolute;
left:100px;
top:35px;
font-size:14px;
}
</style>
</head>
<body>
<div style="width:200px;height:200px;background:green;" id="btn">
<div id="wrap">
<div id='share'>分享</div>
</div>
</div>
<script>
var wrapDiv = document.getElementById('wrap');
wrapDiv.onmouseover = function(){
startMove(0);
};
wrapDiv.onmouseout = function(){
startMove(-100);
};
function startMove(target){
//此处将保存定时器ID的变量在函数中进行定义,问题由此处开始
var timer = null;//如果在全局环境中声明,则问题解除
clearInterval(timer);//此语句没有达到预想的效果
timer = setInterval(function(){
var speed = (target-wrapDiv.offsetLeft)/10;
//speed = speed>0?Math.ceil(speed):Math.floor(speed);//取消注释,修复变速运动的bug
if(wrapDiv.offsetLeft==target){
clearInterval(timer);
}else{
wrapDiv.style.left = wrapDiv.offsetLeft+speed+'px';
}
},50);
}
</script>
</body>
<p></html></p><p>wrapDiv的mouseover可以单独、正常触发;如果之后又触发wrapDiv的mouseout,则会造成该div在触发mouseout时产生晃动。</p><p>对于定时器的其他测试:</p><p>1.例如timer = setInterval(function(){...},time1);</p><p>timer = setInerval(function(){...},time2);</p><p>timer = ...</p><p>此处不会像我们平时声明一个变量后对其初始化,然后在对其赋其他值后销毁原来的值一样,每个定时器依然正常运行;</p><p>2.clearInterval(timer);只会取消改组定时器的最后一次设定的定时器,其他不受影响;</p><p>3.针对定时器的这一情况,建议将保存定时器调用ID的变量在全局作用域中进行声明和初始化;</p>