首页 > 代码库 > 缓速运动封装

缓速运动封装

封装函数

    function animate(obj,endPosition) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var step = ( endPosition- obj.offsetLeft) /10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.style.left = obj.offsetLeft + step + ‘px‘;
            if(obj.offsetLeft == endPosition) {clearInterval(obj.timer)}
        },30)
    }

案例

<!DOCTYLE html>
<html>
<head>
    <meta charset="uft-8" />
    <style>
        #box {width:100px; height: 100px; background:#dfd; position:absolute; left:100px; top:100px;}
    </style>
</head>
<body>
<button id="btn1">200</button>
<button id="btn2">600</button>
<div id="box"></div>
</body>
</html>
<script>
    var btn1 = document.getElementById(btn1);
    var btn2 = document.getElementById(btn2);
    var box = document.getElementById(box);
    btn1.onclick = function () {
        animate(box,200)
    }
    btn2.onclick = function () {
        animate(box,600)
    }
    function animate(obj,endPosition) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var step = ( endPosition- obj.offsetLeft) /10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.style.left = obj.offsetLeft + step + px;
            if(obj.offsetLeft == endPosition) {clearInterval(obj.timer)}//
            //用==不要用>=,否则,在该案例中,如果已经滚动到600位置,再次点击200,将不能回到200位置
            
        },30)
    }
    
</script>

缓速运动封装