多元素运动

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .box{
            width:100px;
            height:100px;
            float:left;
            background:slateblue;
            margin:30px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <script>
        var box = document.getElementsByClassName('box');


        for(var i=0;i<box.length;i++){
            box[i].onmouseover = function(){
                run(this,'height',500,10)
            }

            box[i].onmouseout = function(){
                run(this,'height',100,10)
            }
        }


        function run(ele,attr,target,param) {
            clearInterval(ele.timer);
            ele.timer = setInterval(function () {  // 开启每个元素自己的定时器
                if(attr == 'opacity'){
                    var cur = parseFloat(getStyle(ele, attr)) * 100;  // 透明度
                }else{
                    var cur = parseInt(getStyle(ele, attr));  // 大小,位置等 当前值
                }                
                //  (目标值 - 当前值)/ 缩放比例
                var speed = (target - cur) / param;  // 变速
                speed = speed > 0? Math.ceil(speed) : Math.floor(speed);  // 向右走 变速正数,需要向上取整,反之向左走 变速负数,需要向下取整
                if (cur >= target&& speed>0  || cur<=target && speed<0) {
                    cur = target;
                    clearInterval(ele.timer);
                }

                if(attr == 'opacity'){  // 透明度赋值
                    ele.style[attr] = (cur + speed) / 100;
                }else{
                    ele.style[attr] = cur + speed + 'px';
                }
            }, 50)
        }



        // 获取元素非行间样式
        function getStyle(ele, attr) {
            if (window.getComputedStyle) {  // 标准
                return getComputedStyle(ele)[attr];
            } else {  // ie
                return ele.currentStyle[att];
            }
        }
    </script>
</body>
</html>

效果

原文地址:https://www.cnblogs.com/shihaiying/p/13276033.html