封装运动四:缓冲运动

缓冲运动思想:

改变速度,即给速度除以一个整数即可。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            padding:0;
            margin:0;
        }
       #box{
           width:100px;
           height:100px;
           background: red;
           position:absolute;
           top:100px;
           left:0;
       }
       #target{
           height:400px;
           width:400px;
           border-right:1px solid black
       }

    </style>
</head>
<body>
    <button id = "rbtn">fly</button>
    <button id = "lbtn">back</button>
    <div id = "target"><div id = "box"></div></div>
</body>
</html>
<script src = "tool.js"></script>
<script>
    var oDiv = ById('box');
    var orBtn = ById('rbtn');
    var olBtn = ById('lbtn');
    var timer = null;
    orBtn.onclick = function(){
        divmove(400);
    }
    olBtn.onclick = function(){
        divmove(0);
    }
    function divmove(target){
        clearInterval(timer);
       timer = setInterval(function(){
          var speed = (target - oDiv.offsetLeft)/10;
          //此处会有一个bug,oDiv回不到目标值,所以,需要向上取整、向下取整。
          speed=speed > 0 ? Math.ceil(speed) : Math.floor(speed);
          if( target ==speed){
              clearInterval(timer);
          }else{
              oDiv.style.left = oDiv.offsetLeft + speed + "px" ;
          }
       },30)
    }
</script>

 

posted @ 2019-01-17 14:44  kinoko-木子  阅读(128)  评论(0编辑  收藏  举报