Implementing jQuery's shake effect with animate

前端 未结 9 2488
迷失自我
迷失自我 2020-12-14 10:38

I\'ve been given a cut down subset of the jQuery lib one of the key features I\'m missing is the .effect functions. I do however have .animate. I w

9条回答
  •  隐瞒了意图╮
    2020-12-14 11:04

    I like @phpslightly solution so much, I keep using it. So here it is updated to basic jquery plugin form which will return your element

    jQuery.fn.shake = function(interval,distance,times){
       interval = typeof interval == "undefined" ? 100 : interval;
       distance = typeof distance == "undefined" ? 10 : distance;
       times = typeof times == "undefined" ? 3 : times;
       var jTarget = $(this);
       jTarget.css('position','relative');
       for(var iter=0;iter<(times+1);iter++){
          jTarget.animate({ left: ((iter%2==0 ? distance : distance*-1))}, interval);
       }
       return jTarget.animate({ left: 0},interval);
    }
    

    You would then use it like a regular plugin:

    $("#your-element").shake(100,10,3);
    

    Or use the default values (100, 10, 3):

    $("#your-element").shake();
    

提交回复
热议问题