Javascript 如何抓住;结案;点击事件?

Javascript 如何抓住;结案;点击事件?,javascript,events,click,onclick,popupmenu,Javascript,Events,Click,Onclick,Popupmenu,这里有一个例子。这是谷歌菜单 当您单击齿轮(红十字)时,菜单出现。单击打开菜单(绿色十字)以外的任何位置时,菜单将消失。问题是如何抓住第二个闭幕式(绿十字) 打开菜单很简单 var x = document.getElementById("star"); // this is id of the gear-wheel; var y = document.getElementById("hiddenMenu"); // this is id of the menu wit

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

当您单击齿轮(红十字)时,菜单出现。单击打开菜单(绿色十字)以外的任何位置时,菜单将消失。问题是如何抓住第二个闭幕式(绿十字)

打开菜单很简单

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”标签试过这种方法:


但菜单打开后会立即关闭。首先,当点击“星”时,它变成“块”。但这之后立即变成“无”,因为身体也被点击了。如何解决?是否真的有必要为“body”编写代码以捕获正确的目标事件?

这是由于冒泡/事件传播造成的。
#star
上的侦听器首先触发,然后事件向上冒泡到主体并在那里触发

star.addEventListener("click", closeIfOpen);
document.addEventListener("click", closeIfClickOutsideMenu);

您需要取消事件传播。不幸的是,在没有库的情况下使用内联处理程序并不特别容易

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";
}

这是由于冒泡/事件传播造成的。
#star
上的侦听器首先触发,然后事件向上冒泡到主体并在那里触发


您需要取消事件传播。不幸的是,在没有库的情况下使用内联处理程序并不特别容易

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";
}

使用没有库的内联处理程序并不特别容易。你指的是什么样的图书馆?使用没有库的内联处理程序不是特别容易。你指的是什么样的图书馆?jQuery?是的,这样的解决方案看起来不错,但是“模糊”不能那么容易地应用到div元素上,unfurtunatly@Green为什么不呢?Ugh blur对Div不起作用。好的,你还需要点别的。看起来您需要一个点击处理程序,并检查点击是否在div中是的,这样的解决方案看起来不错,但是“模糊”不能简单地应用于div元素,unfurtunatly@Green为什么不呢?Ugh blur对Div不起作用。好的,你还需要点别的。看起来您需要一个click处理程序,并检查click是否在div中