原生 JavaScript 模仿j Query 缓动动画

原生 JavaScript 模仿j Query 缓动动画

注:适用于各种数值或数值字符串的属性(opacity除外)
HTML部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document测试2</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div id="box"></div>


    <script src="./animate.js"></script>
    <script>
        $("#box").animate({
            width: 1000,
            height: 200,
            marginLeft: '100px'
        }, 100)
    </script>
</body>

</html>

animate函数封装

; (function () {
    // .0 分析原理
    // 目标属性 = 当前属性值+步长
    // 步长=(目标属性值-当前属性值)/数字 【控制速度】

    // 1.0 定义函数 $
    var $ = function (selector) {
        window['element'] = document.querySelector(selector);
        return window;
    };
    // 2.0 在window下 添加方法
    window.animate = function (option, seconds) {
        // .0 清除定时器
        clearInterval(window.element.timer);
        // .0 执行定时器
        window.element.timer = setInterval(function () {
            var bool = true;
            // 循环对象
            for (var propety in option) {
                // 目标值
                var targetValue = parseInt(option[propety]);
                // 当前值
                // getComputedStyle()
                var currenValue = getComputedStyle(window.element)[propety];
                currenValue = parseInt(currenValue); //去除px

                // 计算步长
                var speed = (targetValue - currenValue) / 10;
                // 处理小数点
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                // 判断 如果有一个属性未达到目标值
                if (currenValue != targetValue) {
                    bool = false;
                }
                // 设置元素属性
                window.element.style[propety] = currenValue + speed + 'px';
            }
            // 如果到达目标值 则所有属性都达到目标值
            if (bool) {
                // 清除定时器
                clearInterval(window.element.timer);
                // 执行回调函数
                // if(typeof option){}
            }
        }, seconds)

    }
    // 把$挂载到全局对象下
    window.$ = $;
})()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值