kkk4
2016-06-21 01:53
把onmouseover换成onclick时,第一个clearInterval(timer)就不能起到作用了,有没有同学遇到相同的情况??
<body>
<div id="container">
<div id="box"></div>
</div>
<script type="text/javascript">
window.onload=function(){
var obox=document.getElementById("box");
obox.onclick =function(){
startmove();
}
}
function startmove(){
var timer=null;
clearInterval(timer);
var oc=document.getElementById("container");
setInterval(function(){
if (oc.offsetLeft==0) {
clearInterval(timer);
}
else{
oc.style.left=oc.offsetLeft+1+"px";
}
},30)
}
</script>
</body>
1、var timer=null应该声明在function函数外面。若声明在函数内部,每次调用函数时都会在函数内部声明一个timer变量,且每个timer变量都不相同,所以clearImterval(timer)不起作用。与换成onclick没有关系。
2、timer=setInterval().
第18行应该是timer=setInterval(function(){ 吧。
样式上加上 body{margin:0;padding:0;}
要不然
oc.style.left=oc.offsetLeft+1+"px";这语句只会是每次加9
JS动画效果
113910 学习 · 1502 问题
相似问题