js运动原理2

来源:互联网 发布:python下载安装 编辑:程序博客网 时间:2024/06/05 07:21
<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>
0 0
原创粉丝点击