当前位置: 首页 > 工具软件 > shake > 使用案例 >

封装好的 抖动函数 shake

诸新霁
2023-12-01

  1. 抖动函数shake封装


  2. function shake ( obj, attr, endFn ) {
  3. var pos = parseInt( getStyle(obj, attr) );
  4. var arr = []; // 20, -20, 18, -18 ..... 0
  5. var num = 0;

  6. for ( var i=20; i>0; i-=2 ) {
  7. arr.push( i, -i );
  8. }
  9. arr.push(0);

  10. clearInterval( obj.shake );
  11. obj.shake = setInterval(function (){
  12. obj.style[attr] = pos + arr[num] + 'px';
  13. num++;
  14. if ( num === arr.length ) {
  15. clearInterval( obj.shake );
  16. endFn && endFn();
  17. }
  18. }, 50);
  19. }
  20. function getStyle(obj, attr ){
  21. return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
  22. }



解析: shake ( obj, attr, endFn )
obj --> 抖动对象
attr --> 抖动的方向 top / left 要加引号
endfn --> 回调函数 、 可有可无
ps: attr 传参时 要加 引号


解决连续点击会改变元素的位置示例:给元素身上加个开关

示例:
<!DOCTYPE html><html><head>	<title></title>	<meta charset="UTF-8">	<style>    html,body{margin:0;}     #div1{      width:100px;      height:100px;      background:red;      position:absolute;      margin:50px 100px;     }	</style>  <script>    window.onload=function(){      var adiv=document.getElementById('div1');       adiv.onoff=true;        adiv.onclick=function(){          var a=parseInt(getStyle(adiv,'left'))+parseInt(adiv.offsetLeft)          shake ( adiv,'left', function(){adiv.onoff=true});        }        function shake ( obj, attr, endFn ) {    var pos = parseInt( getStyle(obj, attr) );    var arr = [];           // 20, -20, 18, -18 ..... 0    var num = 0;    for ( var i=20; i>0; i-=2 ) {        arr.push( i, -i );    }    arr.push(0);    if ( obj.onoff) {    clearInterval( obj.shake );    obj.shake = setInterval(function (){             obj.onoff=false;        obj.style[attr] = pos + arr[num] + 'px';        num++;        if ( num === arr.length ) {            obj.onoff==true            clearInterval( obj.shake );            endFn && endFn();        }    }, 50);    }}function getStyle(obj, attr ){ return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr]; }    }  </script></head><body><div id="div1"></div></body></html>








 类似资料: