0

这是一个例子。这是谷歌菜单。

在此处输入图像描述

当您单击齿轮(红十字)时,将出现菜单。当您单击打开的菜单(绿色十字)之外的任何位置时,菜单消失。问题是如何捕捉第二个结束事件(绿十字)。

打开菜单很简单。

var x = document.getElementById("star");          // this is id of the gear-wheel;
var y = document.getElementById("hiddenMenu");    // this is id of the menu with display = none;
x.onclick = function() {
    y.style.display = "block";
}

但是如何让它关闭呢?我使用“body”标签尝试了这种方式:

var bar = document.getElementsByTagName("body")[0];
bar.onclick = function() {
    if (y.style.display == "block") {
       y.style.display = "none";
    }
}

但是菜单在打开后立即关闭。首先它变成了“block”,因为点击了“star”。但是在这之后立即变为“无”,因为也单击了主体。如何解决?是否真的有必要为“body”编写代码来捕捉正确的目标事件?

4

2 回答 2

2
star.addEventListener("click", closeIfOpen);
document.addEventListener("click", closeIfClickOutsideMenu);
于 2012-01-17T19:00:47.287 回答
1

This is due to bubbling/event propagation. The listener on #star fires first, then the event bubbles up to the body and it fires there.

You need to cancel event propagation. Unfortunately this is not particularly easy using inline handlers without a library.

var x = document.getElementById("star");          // this is id of the gear-wheel;
var y = document.getElementById("hiddenMenu");    // this is id of the menu with display = none;
x.onclick = function(e) {
    e = e || window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    }else{
        e.cancelBubble = true;
    }

    y.style.display = "block";
}
于 2012-01-17T19:03:24.620 回答