首页 > 代码库 > 缓冲运动的简单封装

缓冲运动的简单封装

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<style>
    div {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 0;
    }
</style>
<body>
    <button>运动到200</button>
    <button>运动到400</button>
    <div></div>
    <script>
        window.onload=function(){
            var btn = document.getElementsByTagName("button");
            var div = document.getElementsByTagName("div")[0];


            btn[0].onclick = function () {
                animent(div,200);
            }

            btn[1].onclick = function () {
                animent(div,400);
            }

            function animent(ele,target){
                clearInterval(ele.timer);

                ele.timer=setInterval(function(){
                    var speed=(target-ele.offsetLeft)/10;

                    speed=speed>0?Math.ceil(speed):Math.floor(speed);

                    ele.style.left=ele.offsetLeft+speed+"px";
                    console.log(1)

                    if(Math.abs(target-ele.offsetLeft)<=Math.abs(speed)){
                        ele.style.left=target+"px";
                        clearInterval(ele.timer);
                    }

                },10)

            }

        }


    </script>
</body>
</html>

  

缓冲运动的简单封装