JS动画-移入移出

移入移出动画效果的实现主要用到了定时器。定时器即 setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。它会不停地调用函数,直到clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

HTML

<div id="div">
    <span>share</span>
</div>

CSS

div{width: 250px;height: 30px;background-color: blue;position: absolute;left: -200px;top: 50px;}
span{float: right;color: #fff;}

JS,移出效果就是改变该元素绝对定位的 left 的值,判断到了0位置时候结束,清除定时器。移入效果则完全相反。

var oDiv=document.getElementById("div");
oDiv.onmouseover=function(){
    startMove();
};
oDiv.onmouseout=function(){
    startMoveOut();
}
var timer=null;
function startMove(){
    clearInterval(timer);
    var oDiv=document.getElementById("div");
    timer=setInterval(function(){
        if(oDiv.offsetLeft == 0){
            clearInterval(timer);
        }else{
            oDiv.style.left=oDiv.offsetLeft+5+"px";
        }
    },30);
}
function startMoveOut(){
    clearInterval(timer);
    var oDiv=document.getElementById("div");
    timer=setInterval(function(){
        if(oDiv.offsetLeft == -200){
            clearInterval(timer);
        }else{
            oDiv.style.left=oDiv.offsetLeft-5+"px";
        }
    },30);
}

上述代码显然是可以优化的,实现同样功能的函数,可以通过传参来压缩成一个函数。观察两个函数,它们的差别就在于判断的目标位置不同,移动时改变的距离不同。

var oDiv=document.getElementById("div");
oDiv.onmouseover=function(){
    startMove(5,0);
};
oDiv.onmouseout=function(){
    startMove(-5,-200);
}
var timer=null;
function startMove(speed,iTarget){
    clearInterval(timer);
    var oDiv=document.getElementById("div");
    timer=setInterval(function(){
        if(oDiv.offsetLeft == iTarget){
            clearInterval(timer);
        }else{
            oDiv.style.left=oDiv.offsetLeft+speed+"px";
        }
        
    },30);
}

为了提升性能,传参的数量越少越好。比较参数speed和iTarget,其中更重要关键的参数应该是iTarget,可联想日常生活中买火车票必须确定自己的目的地,但是速度无所谓的,因为有绿皮火车,动车,高铁...

var oDiv=document.getElementById("div");
oDiv.onmouseover=function(){
    startMove(0);
};
oDiv.onmouseout=function(){
    startMove(-200);
}
var timer=null;
function startMove(iTarget){
    clearInterval(timer);
    var oDiv=document.getElementById("div");
    timer=setInterval(function(){
        var speed=0;
        if(oDiv.offsetLeft>iTarget){
            speed=-5;
        }else{
            speed=5;
        }
        if(oDiv.offsetLeft == iTarget){
            clearInterval(timer);
        }else{
            oDiv.style.left=oDiv.offsetLeft+speed+"px";
        }  
    },30);
}

移入移出的动画效果实现不是最关键的,主要的是学会对代码的优化是要一步一步的,最大可能精简程序的性能。

猜你喜欢

转载自blog.csdn.net/bertZuo/article/details/84138158
今日推荐