使用JS"晃動"元素


有些網站的登錄表單倘若信息填寫錯誤,除了會給出提示信息之外,還會讓表單左右晃動以提示錯誤,覺得這個效果不錯,便按照自己的思路寫了個DEMO記錄於此。

整個流程就是:

1.設置元素左右晃動的總次數

2.設置元素左右晃動的偏移量范圍並且左右晃動交替進行

3.讓元素開始晃動並記錄次數,元素的移動可以利用絕對定位

4.最后讓元素恢復到初始位置

DEMO代碼

<!DOCTYPE html>
<html>
<head>
<title>shake demo</title>
<meta charset="utf-8"/>
<style type="text/css">
    #wrapper{
        position:relative;
        width:300px;
        margin:150px auto;
    }
    #shaker{
        position:absolute;
        left:0;
        width:300px;
        height:250px;
        border:1px solid #B0B0B0;
        border-radius:3px;
        box-shadow:0 0 10px #B4B4B4;
    }
</style>
<body>
<div id="wrapper">
    <div id="shaker"></div>
</div>
<script type="text/javascript">
/**
 *使登錄表單左右搖晃的對象
 */
function shaking(){
    this.shaker=document.getElementById('shaker');    //搖晃對象為登錄表單
}
shaking.prototype.generator=function(){    //生成左右搖晃的偏移量
    this.offsets=new Array();
    this.times=10;    //登錄表單左右搖晃的總次數
    for(var i=0;i<this.times;i++){    
        var offset=Math.ceil((Math.random()+3)*3);    //9=<偏移量<=12
        if(i%2==0){    //向左的偏移量
            this.offsets.push(offset);
        }
        else{    //向右的偏移量
            this.offsets.push(-offset);
        }
    }
    this.scale=0;    //記錄目前表單已經搖晃的次數
}
shaking.prototype.counter=function(){    //搖晃次數計數器函數
    if(this.scale<this.times){
        var offset=this.offsets[this.scale];
        var position=parseInt(getComputedStyle(this.shaker)['left']);
        var distance=Math.abs(position)+Math.abs(offset);    //表單每次搖晃需要移動的水平距離
        if(offset>0){    //向右偏移
            this.mover(1,distance,this);
        }
        else{    //向左偏移
            this.mover(-1,distance,this);
        }
        this.scale+=1;
        var _this=this;    //緩存當前對象
        setTimeout(function(){_this.counter()},50);
    }
    else{    //表單位置復位
        this.shaker.style.left='0px';
    }
}
shaking.prototype.mover=function(sign,distance){    //搖晃移動函數
    var speed=sign*Math.ceil(distance*0.6);    //表單移動的速度
    this.shaker.style.left=parseInt(getComputedStyle(this.shaker)['left'])+speed+'px';
    distance-=Math.abs(speed);
    var _this=this;    //緩存當前對象
    if(distance>0){    
        setTimeout(function(){_this.mover()},10);
    }
}
var shaker=new shaking();
shaker.generator();
shaker.counter();
</script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM