多元素多属性的链式缓冲

链式运动:

  所谓链式运动,也即元素的可运动属性一个接着一个的发生变化,有其一定的需求性。前面所学的缓动函数无法满足链式运动的需求,缓动函数的叠加与定时器分配(一个元素只有一个定时器)之间构成了矛盾,造成只有最后一个缓动函数有效的局面。

为了能够实现链式运动,需要重新封装缓动函数。整体的思路是,在缓动函数中加一个可选的函数参数,当传入该函数时,则在一个属性变化完成后调用。

这样之后,每个缓动函数后面都可以再跟一个缓动函数,类似于递归,直至不再传递缓动函数。

页面布局和样式部分:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
        #box2{
            width: 100px;
            height: 100px;
            background-color: green;
            position: absolute;
            top: 0;
        }
    
        .aaa{
            border: 1px solid black;
            width: 800px;
            height: 150px;
            position: relative;
        }
        .bbb{
            border: 1px solid black;
            width: 800px;
            height: 150px;
            position: relative;
        }
    </style>
</head>
<body>
    <div class="aaa">
        <div id="box"></div>
    </div>
    <div class="bbb">
        <div id="box2"></div>
    </div>
    
</body>
</html>

js部分:

    var aaa=document.querySelector(".aaa")
    var bbb=document.querySelector(".bbb")
    var obox=document.getElementById("box")
    var obox2=document.getElementById("box2");
    var t;
    aaa.onmouseover=function(){
        move(obox,{left:600},function(){
            move(obox,{top:400},function(){
                move(obox,{left:0},function(){
                    move(obox,{top:0},function(){
                        alert("结束了")
                    });
                })
            })
        })
    }
    aaa.onmouseout=function(){
        move(obox,{left:0})
    }

封装的move函数和获取非行内样式函数:

    function move(ele,obj,callback){
        clearInterval(ele.t);
        ele.t=setInterval(function(){
            var onoff=true;
            for(var i in obj){
                var isNow=parseInt(getStyle(ele,i));
                var speed=(obj[i]-isNow)/7;
                speed=speed>0?Math.ceil(speed):Math.floor(speed);
                if(isNow!=obj[i]){
                    onoff=false;
                }
                ele.style[i]=isNow+speed+"px";
            }
            if(onoff){
                clearInterval(ele.t);
                if(callback){
                    callback()
                }
            }
        },30)
    }
    function getStyle(ele,attr){
        if(ele.currentStyle){
            return ele.currentStyle[attr]
        }else{
            return getComputedStyle(ele,false)[attr]
        }
    }

以下是回掉函数传入的数据改变的页面

1.

扫描二维码关注公众号,回复: 8102483 查看本文章

2.

 .

3

 4

5.

 6.

 

猜你喜欢

转载自www.cnblogs.com/zhouqingfeng/p/11991359.html
今日推荐