繁体   English   中英

jQuery —使用该插件的公共方法停止该插件内的动画

[英]jQuery — stop animation within plugin using public methods of that plugin

我正在使用扩展的jQuery插件样板编写一个具有公共方法的插件,以启动/停止在该插件中运行的动画。 这个动画不是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();一样,它的开始也很好$('.some-elements').wheels();

我想要一种通过调用公共函数来暂停或停止此动画的方法,例如:

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

这个例子将使动画停止一半(我知道超时的不正确性等),但是事实并非如此。 这就是为什么我在这里!

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

我很确定,通过查看jQuery文档 ,我需要在要动画的对象上调用clearQueue()stop() ,在这种情况下,该对象是匿名对象( { i } ),而不是元素),但我不知道如何执行此操作。

任何帮助将非常感激; 我试图尽可能简洁地进行解释,但是如果不清楚,我将尝试在评论中进行澄清!

谢谢!

假设我需要在要动画的对象上调用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()方法可以正常工作。 另外,如果我想暂停/恢复动画,我现在可以使用已经可用的大量暂停/恢复插件。 无需重新编写轮子!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM