我用谷歌搜索并遇到了许多类似的问题,人们试图在 jQuery 插件中设置超时,但我正在努力寻找答案,这不是一篇懒惰的帖子。
我正在尝试延迟调用 animate 以隐藏某些内容,例如,如果用户将鼠标悬停在某个区域上,则更多内容会摆动到 View 中并隐藏原始内容。然后,当用户在 2 秒后将鼠标移开时,将返回原始内容。
动画按预期工作,但忽略了超时。这是我无法理解的!
我们将一如既往地感谢您对代码的任何帮助!
这是简化的代码,专注于动画,但我保留了插件结构:-
;(function($){
$.fn.extend({
pluginName: function(options) {
// - Settings list and the default values
var defaults = {
width: this.css('width'),
};
var options = $.extend({}, defaults, options);
return this.each(function() {
// -- Globals
var o = options;
var timeoutID;
function deceptionAnimate(display) {
if(display == 1) {
obj.clearQueue().animate({
'top': 0,
'left': -o.width
}, o.interval, o.easing);
} else if(display == 0) {
obj.clearQueue().animate({
'top': 0,
'left': 0
}, o.interval, o.easing)
}
}
function delaydeceptionAnimate () {
timeoutID = window.setTimeout(deceptionAnimate(0), 2000);
}
// ---- Initiate
function init() {
// ----- Animate
$(document).on(o.eventTrigger, wrapperID, function() {
deceptionAnimate(1);
});
$(document).on('mouseout', wrapperID, function() {
delaydeceptionAnimate(0);
});
}
// Call
init();
});
}
});
})(jQuery);
最佳答案
window.setTimeout(deceptionAnimate(0), 2000);
您正在调用 deceptionAnimate
并带有参数0
,然后将其返回值(null
)传递给setTimeout
作为要调用的函数。
在这种特殊情况下,您可以像这样重写 deceptionAnimte
:
function deceptionAnimate(display) {
if( display) { /* code to show box */ }
else { /* code to hide box */ }
}
然后使用这个:
window.setTimeout(deceptionAnimate, 2000);
但在更一般的情况下,要将参数传递给要延迟的函数,请使用匿名函数:
window.setTimeout(function() {deceptionAnimate(0);}, 2000);
关于javascript - jQuery 插件中忽略的 setTimeout 时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15006658/