js实现的元素抖动效果代码实例
抖动效果在很多功能中都有应用,比如表单登录密码不正确的话,点击登录按钮就会以抖动的形式进行提示。
下面就通过代码实例介绍一下如何实现此效果。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>犀牛前端部落</title> <style type="text/css"> #body{ text-align:center; } #antzone{ width:200px; position:absolute; margin:10px auto; height:100px; border:2px dotted red; text-align:center } </style> <script type="text/javascript"> function SKclass (obj,Rate,speed) { var oL=obj.offsetLeft; var oT=obj.offsetTop; this.stop=null; this.oTime=null; var om=this; this.start=function(){ if(parseInt(obj.style.left)==oL-2){ obj.style.top=oT+2+"px"; setTimeout(function(){obj.style.left=oL+2+"px"},Rate) } else{ obj.style.top=oT-2+"px"; setTimeout(function(){obj.style.left=oL-2+"px"},Rate) } this.oTime=setTimeout(function(){om.start()},speed); } this.stop=function(){ clearTimeout(this.oTime); } } window.onload=function(){ var m=document.getElementById("antzone"); var nn=new SKclass(m,20,70); var shakeBt=document.getElementById("shake"); var stBt=document.getElementById("st"); shakeBt.onclick=function(){nn.start()} stBt.onclick=function(){nn.stop()} } </script> </head> <body> <div style="margin:10px 200px"> <div><input type="button" id="shake" value="点击抖动"/></div> <div><input type="button" id="st" value="逐渐停止抖动"/></div> <div id="antzone"></div> </div> </body> </html>
上面的代码实现了我们的要求,下面就介绍一下它的实现过程。
一.代码注释:
(1).function SKclass (obj,Rate,speed) {},这是创建一个构造函数,第一个参数是要抖动的元素,第二个和第三个参数都是规定定时器函数延迟多长时间再去执行。
(2).var oL=obj.offsetLeft,在当前代码中是获取元素距离body左侧的距离。
(3).var oT=obj.offsetTop,在当前代码中是获取元素距离body顶部的距离。
(4).this.stop=null,创建一个属性,并赋值为null。
(5).this.oTime=null,这个属性是用作定时器函数的标识。
(6).var om=this,将this值赋值给变量om。
(7).this.start=function(){
if(parseInt(obj.style.left)==oL-2){
obj.style.top=oT+2+"px";
setTimeout(function(){obj.style.left=oL+2+"px"},Rate)
}
else{
obj.style.top=oT-2+"px";
setTimeout(function(){obj.style.left=oL-2+"px"},Rate)
}
this.oTime=setTimeout(function(){om.start()},speed);
},这段代码的功能就是让元素向左和向上2px范围内抖动。
最后一局是采用递归的方式调用this.start()方法,这样就实现了持续抖动。
(8).this.stop=function(){
clearTimeout(this.oTime);
},停止定时器函数的执行。
二.相关阅读:
(1).构造函数可以参阅javascript构造函数简单介绍一章节。
(2).offsetLeft可以参阅js offsetLeft一章节。
(3).parseInt()方法可以参阅javascript parseInt()一章节。
(4).setTimeout()方法可以参阅setTimeout()一章节。
(5).new运算符的作用可以参阅js new运算符一章节。