1

我在谷歌上搜索并遇到了许多类似的问题,人们试图在 jQuery 插件中设置超时但我正在努力寻找答案,这不是一个懒惰的帖子。

我试图在调用动画以隐藏某些内容时实现延迟,例如,如果用户将鼠标悬停在某个区域上,则会有更多内容进入视图并隐藏原始内容。然后,当用户在 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);
4

2 回答 2

4
window.setTimeout(deceptionAnimate(0), 2000);

您正在使用参数调用 ,然后将其返回值 ( )作为要调用的函数传递给。deceptionAnimate0nullsetTimeout

在这种特殊情况下,您可以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);
于 2013-02-21T15:59:24.853 回答
0

您需要注意如何编写超时函数调用。在这里,您实际上是在调用 delayDeceptionAnimate 而不是将其作为函数属性传递给 setTimeout 函数。

尝试像这样重写该块:

function delaydeceptionAnimate () {
    timeoutID = window.setTimeout(function() {
        deceptionAnimate(0);
        }, 2000);
}

这样,您将传递一个回调函数,然后调用 delayDeceptionAnimate 函数!

于 2013-02-21T16:06:59.260 回答