码迷,mamicode.com
首页 > Web开发 > 详细

js 封装一个动画函数

时间:2019-03-26 15:24:21      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:code   否则   直接   rto   目标   大于   math   class   bsp   

//动画函数---任意一个元素移动到指定的目标位置
    //element为元素 target为位置
    function carToon(element, target) {
        //设置一个定时器让他循环去增加
         element.timeid = setInterval(function () {
            //拿到当前的位置(纯数字)
            var current = element.offsetLeft;
            //每次要移动的像素current
            var step = 10;
            //注意 这里是判断到底往那边走 如果当前的位置大于目标位置那么就往回走(往左边走 就是负的像素)
            //否则 当前位置小于目标地址 就继续往右走(正数的像素)
             step = current > target ? -step : step;
            //这里是移动之后的位置
             current += step;
            //判断目标位置-当前的位置是否大于每次走的像素
            if (Math.abs(target - current) > Math.abs(step)) {
                //继续移动
                element.style.left = current + ‘px‘;
            } else {
                //目标位置-当前的位置小于每次走的像素.清理定时器 然后让它直接移动到目标的位置
                clearInterval(element.timeid);
                element.style.left = target + ‘px‘;
            }
        }, 10)
    }

 

js 封装一个动画函数

标签:code   否则   直接   rto   目标   大于   math   class   bsp   

原文地址:https://www.cnblogs.com/wanguofeng/p/10600021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!