您好,欢迎来到哈瑞养生。
搜索
您的当前位置:首页js如何实现缓冲运动(代码实例)

js如何实现缓冲运动(代码实例)

来源:哈瑞养生


本篇文章给大家带来的内容是关于js如何实现缓冲运动(代码实例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

缓冲运动的特性

  • 逐渐变慢,最后停止

  • 距离越远速度越大

  • 速度由距离决定

  • 速度=(目标值-当前值)/缩放系数

  • 距离大,速度大。
    距离小,速度小。
    速度和距离成正比。
    缓冲运动的时候速度一定要取整,如果速度0.9的话,不取整会直接变成0;速度大于0应向上取整,小于0应向下取整。
    下面我们就来做一个div从0移动到300的缓冲运动,做一个div从600移动到300的缓冲运动。

    代码实现缓冲运动

    <!DOCTYPE html>
    <html>
     <head>
     <title>缓冲运动</title>
     <style>
     #div1{
     width: 100px;
     height: 100px;
     background: red;
     position: absolute;
     /* left: 0; */
     left: 600px;
     top: 50px;
     }
     #div2{
     /* 300位置的参考线 */
     width: 1px;
     height: 300px;
     position: absolute;
     left: 300px;
     top: 0;
     background: #000;
     }
     </style>
     <script>
     window.onload=function(){
     var oBtn=document.getElementById("btn1");
     oBtn.onclick=function(){
     startMove();
     }
     }
    
     function startMove(){
     var oDiv=document.getElementById("div1");
     setInterval(function(){
     var speed=(300-oDiv.offsetLeft)/10;
     speed=speed>0?Math.ceil(speed):Math.floor(speed);//取整
     oDiv.style.left=oDiv.offsetLeft+speed+"px";
     },30);
     }
     </script>
     </head>
     <body>
     <input id="btn1" type="button" value="开始运动" />
     <div id="div1"></div>
     <div id="div2"></div>
     </body>
    </html>

    Copyright © 2019- harx.cn 版权所有

    违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

    本站由北京市万商天勤律师事务所王兴未律师提供法律服务