为什么我的关闭定时器不起效果
var timer=null;
function startMove(){
var divv=document.getElementById("div1");
setInterval(function(){
if (divv.offsetLeft==0) {
clearInterval(timer);
}else{
divv.style.left=divv.offsetLeft+10+'px';
}
},30)
}
var timer=null;
function startMove(){
var divv=document.getElementById("div1");
setInterval(function(){
if (divv.offsetLeft==0) {
clearInterval(timer);
}else{
divv.style.left=divv.offsetLeft+10+'px';
}
},30)
}
2017-02-24
function startMove() {
var divv = document.getElementById("div1");
clearInterval(timer);//最开始需要清空一下,否则以前执行会留有缓存
timer = setInterval(function() { //指定timer的值,否则要怎么清空
if (divv.offsetLeft == 0) {
clearInterval(timer);
} else {
divv.style.left = divv.offsetLeft + 10 + 'px';
}
}, 30)
}
//如果这样还是解决不了问题说明css有问题,是不是添加了border之类的属性等等。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定时器</title>
<style type="text/css">
*{padding: 0;
margin: 0}
div {
position: absolute;
left: -200px;
width: 400px;
height: 50px;
background: #59B24F;
}
</style>
<script type="text/javascript">
window.onload = function() {
var divv = document.getElementById("div1");
divv.onmouseover = function() {
startMove();
}
var timer = null;
function startMove() {
clearInterval(timer);
timer = setInterval(function() {
if (divv.offsetLeft == 0) {
clearInterval(timer);
} else {
divv.style.left = divv.offsetLeft + 1 + 'px';
}
}, 30)
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
举报