用animate实现jQuery的震动效果

wmi*_*ell 14 javascript jquery jquery-animate

我已经获得了jQuery lib的一个减少的子集,我缺少的一个关键特性是.effect函数.但我有.animate.我想知道是否有人会有任何想法如何再现动画功能.

因为我需要保持代码大小,所以我特别想要这几行.这就是为什么jquery lib尽可能小,并且没有效果函数.

TLDR - 我正在尝试更换

 $("#"+id_string).effect( "shake", {}, "fast" );
Run Code Online (Sandbox Code Playgroud)

.animate在jQuery中使用一些东西.

wmi*_*ell 45

到目前为止我有这样的事情..

jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
    this.each(function() {
        $(this).css("position","relative"); 
        for (var x=1; x<=intShakes; x++) {
        $(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
    .animate({left:intDistance}, ((intDuration/intShakes)/2))
    .animate({left:0}, (((intDuration/intShakes)/4)));
    }
  });
return this;
};
Run Code Online (Sandbox Code Playgroud)

  • 所有那些parens ......`(((``为什么? (3认同)
  • @Fresheyeball 大多数这些括号都是不需要的,这就是我的观点。例如,这个 - `(((intDuration/intShakes)/4))` - 可以替换为这个 - `intDuration/intShakes/4` - 无需改变操作顺序。另外,请注意双重包装 - `((expression))` - 它没有任何作用。 (2认同)

Nic*_*ver 9

它实际上已经以这种方式实现了jquery.effects.shake.js,如果你只想复制那些功能,你可以确切地看到它是如何实现的.

另一种思考方法:如果你使用多种效果,我建议你只使用你想要的效果下载jQuery UI.对于这种效果,如果不自行复制功能,您只需要jquery.effects.core.jsjquery.effects.shake.js.

  • 新链接:[jquery.ui.effect.js](https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.effect.js)和[jquery.ui.effect.shake的.js](https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.effect-shake.js) (5认同)
  • 新的链接:[effect.js](https://github.com/jquery/jquery-ui/blob/master/ui/effect.js)和[effect-shake.js](https://github.com /jquery/jquery-ui/blob/master/ui/effect-shake.js) (3认同)
  • 新的链接[effect.js](http://stackoverflow.com/questions/4399005/implementing-jquerys-shake-effect-with-animate)和[effect-shake.js](https://github.com/的jquery/jQuery的UI /斑点/主/ UI /效果/效果-shake.js) (2认同)

el *_*cer 8

我非常喜欢@phpslightly解决方案,我一直在使用它.所以这里它更新为基本的jquery插件表单,它将返回你的元素

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);
}
Run Code Online (Sandbox Code Playgroud)

然后你会像常规插件一样使用它:

$("#your-element").shake(100,10,3);
Run Code Online (Sandbox Code Playgroud)

或者使用默认值(100,10,3):

$("#your-element").shake();
Run Code Online (Sandbox Code Playgroud)


nin*_*out 6

这可能与现在无关,但我已将jQ UI的震动效果移植为独立的jQuery插件.所有你需要的是jQuery,它的工作方式与jQ UI中提供的完全相同.

对于那些想要使用效果而没有实际膨胀他们的项目与不必要的jQ UI核心文件的人.

$('#element').shake({...});

它可以在这里找到指令:https://github.com/ninty9notout/jquery-shake

以为我会留在这里供将来参考.