<!DOCTYPE?html>
<html>
<head>
<meta?charset="UTF-8">
<title>Insert?title?here</title>
<style?type="text/css">
div{
width:200px;
height:200px;
background:#ccc;
position:absolute;
left:0;
top:50px;
}
</style>
</head>
<body>
<script?type="text/javascript">
var?timer;
function?divMove(){
var?speed=2;
var?bt1=document.getElementById('bt1');
/*1.為什么下面這一行必須放在divMove里面才能確保div能移動?,而放在divMove外面整個運動都進行不了了?,
??2.這一行只是取div而已,在外面當做全局變量來用,不行嗎,
??3.bt1放在外面怎么就沒有影響*/
var?oDiv=document.getElementById('div1');
clearInterval(timer);
timer=setInterval(function(){
if(oDiv.offsetLeft>=400){
clearInterval(timer);
}else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30)
oDiv.onmouseover=function(){
clearInterval(timer);
}
}
</script>
<input?id='bt1'?type="button"?value='start?run'?onclick='divMove()'>
<div?id='div1'></div>
</body>
</html>
javascript實現(xiàn)div運動的代碼中,一行代碼位置不同,效果不同,這里是為什么呢?(具體見注釋))
白小凡
2016-12-12 16:05:25