我正在使用extended jQuery Plugin Boilerplate编写一个具有公共(public)方法的插件来启动/停止插件内运行的动画;顺便说一句,这个动画不是 CSS amin,它只是一个计数器,因此我可以使用每个 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();
这样调用时,启动效果很好.
我想要一种通过调用公共(public)函数来暂停或停止此动画的方法,例如:
var timeout = window.setTimeout(function () {
$('#total.cont-email-wheel').wheels('stop');
}, 500);
这个例子会在一半左右停止动画(我理解超时等不准确的情况),但事实并非如此;这就是我来这里的原因!
注意:stop
在中间标记附近记录到控制台,因此该方法正在正确调用。
通过查看 jQuery docs 我很确定我需要打电话clearQueue()
和stop()
在正在动画的对象上,在本例中是一个匿名对象( { i }
),而不是元素,但我不知道如何执行此操作。
任何帮助将不胜感激;我已尝试尽可能简洁地解释,但如果不清楚,我会尝试在评论中进行澄清!
谢谢!
最佳答案
看来我的假设是正确的,我需要在正在动画的对象上调用 clearQueue
和 stop
方法,因此我扩展了 this.element
具有属性 i
,这样我就可以为其设置动画,而不是匿名对象。
这意味着我现在可以调用 clearQueue
和 stop
方法来暂停 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();
}
};
通过这样做,我现在不需要自己的公共(public)方法来停止动画,因为 jQuery 的 native stop()
方法就可以正常工作。另外,如果我想暂停/恢复动画,我现在可以使用已有的大量暂停/恢复插件。无需重新编写轮子!
关于javascript - jQuery - 使用该插件的公共(public)方法停止插件内的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15221825/