1.抖动的实现原理: a.通过获取元素的位置left,用定时器改变left; b.把一组数据(改变left的),比如16,-16,14,-14….0存到数组里 c.然后开个计时器把数组里的数字分别与原left值计算赋给left.最后数组走完的时候把计时器关闭
代码如下:
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> #div1{width:100px; height:100px; background-color:red; position:absolute; left:40px; top:40px;} </style> </head> <body> <input type="button" value="抖起来" id="btn"/> <div id="div1"></div> <script> var arr=[]; for(var i=16;i>0;i-=2){ arr.push(i,-i); } arr.push(0); var onOff = true; $('btn').onclick = function(){ if(onOff){ clearTimeout($('div1').timer2); var nowLeft = parseInt(getStyle($('div1'),'left')); var i = 0; clearInterval($('div1').timer1); $('div1').timer1 = setInterval(function(){ doMove($('div1'),16,arr[i]+nowLeft,'left'); if(i == arr.length-1){ clearInterval($('div1').timer1); }else{ i++; } },60) onOff = false; $('div1').timer2 = setTimeout(function(){ onOff = true; },60*(arr.length+1))//此处代码是为了可以重复多次地实现点击后出现抖动效果;“60*(arr.length+1))”是约束在完成一次抖动全过程之后,下一次抖动才可发生;这可以避免因为多次点击从而引起位置错乱的问题 } } function $( v ){//$为函数名 if( typeof v === 'function' ){ window.onload = v; } else if ( typeof v === 'string' ) { return document.getElementById(v); } else if ( typeof v === 'object' ) { return v; } } function getStyle( obj, attr ){ return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle( obj )[attr]; } function doMove(id,speed,where,howTo,endFn){ speed = parseInt(getStyle( id, howTo ))> where ? -speed : speed; clearInterval(id.timer); id.timer=setInterval(function(){ var nowLeft = parseInt(getStyle( id, howTo )); var thisLeft = nowLeft+ speed; if(thisLeft >=where&&speed>0||thisLeft <=where&&speed<0){ thisLeft=where; } id.style[howTo] = thisLeft+'px'; if(parseInt(getStyle( id, howTo ))===where){ clearInterval(id.timer); endFn&&endFn(); } },30) } </script> </body> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768