jQuery - 使用该插件的公共方法在插件中停止动画

时间:2013-03-05 10:47:12

标签: javascript jquery jquery-plugins jquery-animate

我正在使用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 }),而不是元素,但我不知道如何做到这一点。

非常感谢任何帮助;我试图尽可能简明扼要地解释,但如果不清楚我会在评论中澄清一下!

谢谢!

1 个答案:

答案 0 :(得分:0)

似乎我认为我需要在动画对象上调用clearQueuestop方法,因此我使用属性this.elementi进行了扩展,这是正确的。我可以设置动画而不是匿名对象。

这意味着我现在可以调用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()方法将正常工作。此外,如果我想暂停/恢复动画,我现在可以使用已经可用的过多暂停/恢复插件。无需重新编写方向盘!

相关问题