0

我在 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 示例。(如果您在小提琴中取消回调函数,您会看到边框正确变为红色但回调失败。)
现在谢谢...

4

2 回答 2

3

干得好:

$.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/

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

此外,我推荐一个 CSS 类用于“摇晃”状态:

.shaking { border-color: red; }

另外,请注意我对$.fn.shake. 我建议您花几分钟时间来分析一下我是如何改进代码的。

于 2011-11-12T02:20:30.297 回答
1

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

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

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

于 2011-11-12T01:25:48.393 回答