<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
*{margin: 0;padding: 0;}
ul{list-style: none;}
li{width: 200px;height: 100px;background: #8B4513;margin-top: 10px;}
</style>
<script type="text/javascript">
window.onload=function(){
var lia=document.getElementsByTagName("li");
for(var i=0;i<lia.length;i++){
lia[i].timer=null;
lia[i].onmouseover=function(){
startMove(this,400);
}
lia[i].onmouseout=function(){
startMove(this,200);
}
}
}
function startMove(obj,target){
clearInterval(obj.timer);
var speed=(target-obj.offsetWidth)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
obj.timer=setInterval(function(){
if(obj.offsetWidth==target){
clearInterval(obj.timer);
}else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},30)
}
</script>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
用控制台查了一下,你的speed 是不变的,这样的话,if(obj.offsetWidth==target)有可能永远都不满足,例如:用速度9从两百运动到400,会刚好错过400这个值,计时器就一直没被清除。
解决方法:
把speed的计算放进setInterval里面的那个参数下
代码:
function startMove(obj,target){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var speed=(target-obj.offsetWidth)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth==target){
clearInterval(obj.timer);
}else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},30)
}
感觉没啥地方出错啊,要不你去看下源码吧