将回调function添加到自定义JQuery动画的真正方法是什么?

我在stackoverflow问题中找到了一个震动效果( 这里 )
代码如下;

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; }; 

但是我需要一种方法来添加一个回调函数(或任何其他简单的方法),用于在效果之前追逐抖动元素的边框颜色,并在动画编译后切换到原始颜色。
我尝试下面但没有机会(边框立即变成原色)

 jQuery.fn.shake = function(intShakes, intDistance, intDuration,callback) { 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))); } }); if(callback) callback(); return this; }; 

并像这样打电话

 $elem.css('borderColor','red'); $elem.shake(3,5,500,function(){ $elem.css('borderColor','#a6caf0');}) 

你可以在这里找到一个JSFiddle示例。(如果在小提琴中取消回调函数,你会看到边框正确变为红色但回调失败。)
Thaks现在……

干得好:

 $.fn.shake = function ( times, distance, duration, callback ) { return this.css({ position: 'relative' }).each( function () { for ( var i = 0, t = duration / times; i < times; i+= 1 ) { $( this ). animate({ left: -distance }, t / 3 ). animate({ left: distance }, t / 3 ). animate({ left: 0 }, t / 4 ); } $( this ).show( callback ); }); }; 

然后...

 $( button ).click( function () { $( field ).addClass( 'shaking' ).shake( 5, 10, 500, function () { $( this ).removeClass( 'shaking' ); }); }); 

现场演示: http //jsfiddle.net/f96ff/8/

不需要计时器。 您只需通过(中性) .show()方法将callback函数添加到效果队列。 这确保仅所有动画(来自队列)完成后才调用callback

另外,我推荐一个用于“摇动”状态的CSS类:

 .shaking { border-color: red; } 

另外,请注意我显着重构了$.fn.shake的代码。 我建议你花几分钟的时间来分析我如何改进代码。

你必须设置超时,你不能直接调用回调,因为jquery的animate函数是异步的。 所以它会直接执行回调。 可以做的是将超时设置为整个动画的时间。

你也不能只使用jQuery的animate函数的回调,因为你使用的是多个。

解决方案: http : //jsfiddle.net/f96ff/2/