JS封装单样式动画

 <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
        }
    </style>
<div class="box"></div>
  //单样式动画封装
        // 参数:元素,要变化的样式,目标值
        function animate(el, target, styleName) {
            if (el.timer) {
                clearInterval(el.timer)
            }
            if (styleName == 'opacity') {
                target = target * 100
            }
            el.timer = setInterval(function () {
                var obj = getComputedStyle(el, null);//返回style样式
                if (styleName = 'opacity') {
                    var start = parseInt(obj[styleName] * 100)
                } else {
                    var start = parseInt(obj[styleName])//去掉px
                }
                //修正步长
                var step = (target - start) / 10
                if (Math.abs(step) < 1) {
                    step = step > 0 ? 1 : Math.floor(step)
                }
                if (styleName = 'opacity') {
                    el.style.opacity = (start + step) / 100
                } else {
                    // obj.styleName; 错误写法 styleName此时是变量
                    el.style[styleName] = start + step + 'px';
                }
                //达到终止条件
                if (target == step + start) {
                    clearInterval(el.timer)
                    el.timer = null
                }
            }, 16.7)
        }


        var box = document.querySelector('.box');
        box.onclick = function () {
            animate(box, 0.3, 'opacity')
        }

上一篇:网友悼念:为你逝去的生命哭泣(英文)


下一篇:[ linux ] vim 编辑器的三种模式介绍