您的位置:首页 > Web前端 > JavaScript

js运动原理2

2016-05-09 08:56 447 查看
<html>

<head lang="en">

<meta charset="UTF-8">

<title></title>

<style>

#div1{

width: 100px;

height: 100px;

background: red;

position:absolute;

top: 50px;

left:0;

}

#div2{

width: 100px;

height: 100px;

background: red;

position:absolute;

top: 250px;

left:600px;

}

</style>

</head>

<body>

<input id="bt1" type="button" value="开始向右">

<input id="bt2" type="button" value="开始向左">

<div id="div1"></div>

<script type="text/javascript">

var oBt2=document.getElementById("bt2");

var oDiv1Timerid=null;

var oBt=document.getElementById("bt1");

oBt.onclick= function () {

var oDiv=document.getElementById("div1");

clearInterval(oDiv1Timerid); //1. 启动定时器之前,需要清理之前的定时器。

oDiv1Timerid=setInterval(function(){//启动定时器,并记录返回值(定时器的标识)

//做运动的部分 和 清理定时器的部分, 放在 if else 里面

if(oDiv.offsetLeft>600){

//清理定时器的 条件 。要注意边界判断!

clearInterval(oDiv1Timerid);

}

else{

oDiv.style.left=oDiv.offsetLeft+9+"px";

}

},30);

}

oBt2.onclick= function () {

var oDiv=document.getElementById("div1");

clearInterval(oDiv1Timerid);

oDiv1Timerid=setInterval(function(){

if(oDiv.offsetLeft<0){

clearInterval(oDiv1Timerid);

}

else{

oDiv.style.left=oDiv.offsetLeft-9+"px";

}

},30);

}

</script>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: