匀速运动案例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <style>
        .box{
            100px;
            height:100px;
            background-color: green;
            position:absolute;
            left:0;
            top:100px;
        }
    </style>
</head>
<body>
        <div class="box " id="demo"></div>
        <button id="btn">开始</button>
</body>
</html>
<script>
    //点击开始按钮,盒子匀速向右边直线运动,到了距离左边500px 的时候自动停下来
    var demo=document.getElementById("demo");
    var btn=document.getElementById("btn");
    var Timer=null;
    var num=0;
    btn.onclick=function()
    {
        Timer=setInterval(fn , 4);
        function fn()
        {
            num++
            if(num<=500)
            {
                demo.style.left=num+"px";
            }
            else{
                clearInterval(Timer); //定时器清除就等于停止运动了。
            }
        }

    }
</script>

  

原文地址:https://www.cnblogs.com/shanlu0000/p/11228664.html