[英]How to catch “closing” click event?
這是一個例子。 這是Google菜單。
單擊齒輪(紅叉)時,將顯示菜單。 當您單擊打開的菜單(綠色叉號)以外的任何位置時,菜單都會消失。 問題是如何捕捉第二次閉幕事件(綠色十字)。
打開菜單很簡單。
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";
}
}
但是菜單打開后立即關閉。 首先,當單擊“星號”時,它變為“塊”。 但是,在此之后,由於單擊了主體,因此“無”。 怎么解決呢? 是否真的有必要為“ body”編寫代碼以捕獲正確的目標事件?
star.addEventListener("click", closeIfOpen);
document.addEventListener("click", closeIfClickOutsideMenu);
這是由於冒泡/事件傳播。 #star
上的偵聽器#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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.