【问题标题】:What is the true way of adding callback functionality to custom JQuery Animation?将回调功能添加到自定义 JQuery 动画的真正方法是什么?
【发布时间】:2011-11-12 01:08:13
【问题描述】:

我在 stackoverflow 问题中发现了抖动效果 (here)
代码如下;

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

【问题讨论】:

  • 查看 jsFiddle 中的“整理”按钮...
  • @ŠimeVidas - 在哪里?我从来没有听说过。
  • @JaredFarrish 在上方工具栏中的 jsFiddle 中...它在按钮上。
  • @ŠimeVidas - 圣牛,太棒了。我实际上(他)在看萤火虫。我当时想,在哪里???
  • @Šime Vidas - 我做了,但代码看起来已经很整洁了..

标签: jquery animation callback effect shake


【解决方案1】:

给你:

$.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 的代码进行了重大重构。我建议您花几分钟的时间来分析一下我是如何改进代码的。

【讨论】:

  • @alper - 我不赞成你接受的答案的原因是因为我本能地不接受timeout 方法。我希望你能看到这个答案。
  • 哇,它看起来很漂亮,正如我之前提到的,我正在尝试更深入地学习。感谢您提供的纯(完美)JQuery 解决方案。
【解决方案2】:

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

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

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

【讨论】:

  • Šime Vidas 资助了一种使用纯 JQuery 的更好方法,但再次感谢您快速有效的回答。
猜你喜欢
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
相关资源
最近更新 更多