其他分享
首页 > 其他分享> > 封装变速动画

封装变速动画

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: lightcoral;
            position: absolute;
            margin-top: 30px;
            left: 0px;

        }
    </style>
</head>
<body>
<button id="btn1">点击移动到400px</button>
<button id="btn2">点击移动到800px</button>
<div id="box"></div>
<script src="common.js"></script>
<script>
    //封装变速动画
    //@params : 元素  目标位置
    function animateBian(element, target) {
        clearInterval(element.timeId);
        element.timeId = setInterval(function () {
            //获取当前的元素的位置
            var current = element.offsetLeft;
            //设置移动的步数
            var step = (target - current)/10;
            //判断步数 > 0, 则向上取整 ,否则向下取整
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            //获取每次移动后的left值
            current += step;
            element.style.left = current + "px";
            if(current == target){
                clearInterval(element.timeId);
            }
            console.log("目标位置:" + target + ",每次移动的步数" + step +",当前位置:" + current );
        },10)
    }

    my$("btn1").onclick = function () {
        animateBian(my$("box"), 400);
    }
    my$("btn2").onclick = function () {
        animateBian(my$("box"), 800);

    }


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

 

标签:function,动画,封装,target,element,current,step,变速,my
来源: https://www.cnblogs.com/Ironman725/p/10920726.html