开发者

JQuery if hovering on either element

So I have 2 divs. One is "top" and one is "menu." I got "menu" to fade in when you hover on "top" in JQuery, as shown:

$(".top").mouseover(function(){
    $(".menu").fadeIn(200);
});

$(".top").mouseout(function开发者_StackOverflow社区(){
    $(".menu").fadeOut(200);
});

But I want to make it so if I'm also hovering on "menu," "menu" will stay faded in. How would I do this?


I believe this will do it for you. It waits half a second before hiding the menu. If the user hovers over the menu in that time, then it cancels the hide operation.

var timer;

$(".top").mouseover(function(){
    clearTimeout(timer);
    $(".menu").fadeIn(200);
});

$(".top, .menu").mouseout(function(){
    timer = setTimeout(function() {
        $(".menu").fadeOut(200);
    }, 500);
});

$(".menu").mouseover(function() {
    clearTimeout(timer);
});


Add a variable that remembers if you are hovering on the menu:

var isHoveringMenu;

$(".menu").mouseover(function(){
    isHoveringMenu = true;
});

$(".menu").mouseout(function(){
    isHoveringMenu = false;
    $(".menu").fadeOut(200); // you probably want this here
});

$(".top").mouseover(function(){
    $(".menu").fadeIn(200);
    isHoveringMenu = true; // not necessary, but sounds good
});

$(".top").mouseout(function(){
    if (!isHoveringMenu) {
        $(".menu").fadeOut(200);
    }
});

You may want to tweak this slightly -- the best solution depends on the spatial relationship between the two divs, so we 'd need to see the layout first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜