简体   繁体   English

如何为jQuery函数正确设置“ settimeout”?

[英]How to set up a “settimeout” properly for a jQuery function?

I hope I can get some help. 希望我能有所帮助。 I'm new to Jquery and JavaScript and I got stuck with a "setTimeout" function. 我是Jquery和JavaScript的新手,但我陷入了“ setTimeout”函数的困境。 I'm working on my navigation bar and basically I need a div(sub menu) to fade in when "click" on an anchor tag, fade it out if you move the mouse to a different navigation link and hide it all together if the mouse leaves it: like so: 我正在导航栏上工作,基本上我需要一个div(子菜单)以在“单击”锚标签时淡入,如果将鼠标移至其他导航链接则将其淡出,如果将鼠标隐藏到一起,则将其全部隐藏鼠标离开它:像这样:

  1. show on click but hide it after a couple of seconds 点击显示,但几秒钟后将其隐藏

  2. hide if after the mouse leaves the div. 如果鼠标离开div后隐藏。

This is what I've got so far: 到目前为止,这是我得到的:

$("a").click(function() {
    $("#sub_nav").fadeIn(400);
});

$("#sub_nav").mouseleave(function() {
    $(this).fadeOut(0);
});

$("#sub_nav").mouseenter(function() {
    if(this) {
        $(this).show(0);
    } else {
        setTimeout(function() {
            $(this).fadeOut(0);
        }, 2000);
    };
});

It works as expected except for the setTimeout . 除了setTimeout以外,它setTimeout预期工作。

Appreciate all the help I can get. 感谢所有我能得到的帮助。

$("#sub_nav").mouseenter(function() {
    if ( !$(this).is(':animated') ) {
        var el = this;
        setTimeout(function() {
            $(el).fadeOut(0);
        }, 2000);
    }
});

'this' inside the scope of the function fed is the 'window' object, you need to save the reference to the element. 馈送功能范围内的“ this”是“ window”对象,您需要保存对元素的引用。

I removed your if(this) because it would always evaluate to true and I wasn't sure if you were debugging, but you can probably use this as an example if it isn't the correct solution. 我删除了您的if(this),因为它始终会评估为true,并且不确定是否要调试,但是如果它不是正确的解决方案,则可以使用它作为示例。

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

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