【问题标题】:jQuery -- stop animation within plugin using public methods of that pluginjQuery——使用插件的公共方法停止插件内的动画
【发布时间】:2013-02-19 17:41:55
【问题描述】:

我正在使用extended jQuery Plugin Boilerplate 编写一个插件,该插件具有启动/停止在插件内运行的动画的公共方法;这个动画不是 CSS amin BTW,它只是一个计数器,所以我可以使用每个 step 上的函数触发另一个方法。

动画从init()方法内部开始:

Plugin.prototype = {
    init: function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
        // you can add more functions like the one below and
        // call them like so: this.yourOtherFunction(this.element, this.options).
        console.log('init');

        $({ i: 0 }).animate({ i: 1000 }, {
            duration: 1000
        ,   step:     function () { console.log(this.i); }
        });
    },
    stop: function () { //yourOtherFunction: function () {
        // some logic
        console.log('stop');

        $(this.element).clearQueue();
        $(this.element).stop();
    }
};

当像$('.some-elements').wheels(); 这样调用时,确实开始得很好。

我想通过调用公共函数来暂停或停止此动画,例如:

var timeout = window.setTimeout(function () {
    $('#total.cont-email-wheel').wheels('stop');
}, 500);

这个例子会在中途停止动画(我理解超时等的不准确性),但事实并非如此;这就是我在这里的原因!

注意:stop 在中途标记附近被记录到控制台,因此该方法被正确调用。

我很确定,通过查看jQuery docs,我需要在动画对象上调用clearQueue()stop(),在本例中是匿名对象 ({ i }),而不是元素,但我不知道该怎么做。

任何帮助将不胜感激;我试图尽可能简洁地解释,但如果不清楚,我会尝试在 cmets 中澄清!

谢谢!

【问题讨论】:

    标签: javascript jquery jquery-plugins jquery-animate


    【解决方案1】:

    假设我需要在动画对象上调用 clearQueuestop 方法似乎是正确的,因此我使用属性 i 扩展了 this.element 以便我可以动画它而不是匿名对象。

    这意味着我现在可以调用clearQueuestop 方法来暂停this.element 对象上的动画,可以从插件中的任何方法访问该对象。

    Plugin.prototype = {
        init: function () {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.options).
            console.log('init');
    
            $.extend(this.element, { i: 0 });
    
            $(this.element).animate({ i: 1000 }, {
                duration: 1000
            ,   step:     function () { console.log(this.i); }
            });
        },
        stop: function () { //yourOtherFunction: function () {
            // some logic
            console.log('stop');
            console.log($(this.element));
    
            $(this.element).clearQueue();
            $(this.element).stop();
        }
    };
    

    通过这样做,我现在不需要我自己的公共方法来停止动画,因为 jQuery 的原生 stop() 方法可以正常工作。此外,如果我想暂停/恢复动画,我现在可以使用大量可用的暂停/恢复插件。无需重新编写轮子!

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 2011-11-23
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2011-11-27
      • 1970-01-01
      相关资源
      最近更新 更多