2012-01-17 146 views
0

下面是一個例子。這是Google菜單。如何捕捉「關閉」點擊事件?

enter image description here

當你點擊齒輪輪(紅叉)出現的菜單。當您點擊打開菜單(綠色十字)以外的任何地方時,菜單消失。問題是如何捕捉第二個結束事件(綠色十字)。

打開菜單很簡單。

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

但是如何使它關閉?我試着用「身體」的標籤是這樣的:

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

但它已被打開後立即關閉菜單。首先,點擊「星號」後變成「塊」。但隨着身體也被點擊,這成爲「無」之後。如何解決它?爲了捕捉正確的目標事件,編寫「body」代碼真的有必要嗎?

回答

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

是的,這樣的解決方案看起來不錯,但「模糊」不能applyed到div元素這麼簡單,unfurtunatly – Green 2012-01-18 10:21:45

+0

@Green爲什麼不呢?呃模糊不適用於div。好的,你需要別的東西。看起來你需要一個點擊處理程序,並檢查點擊是否在div – Raynos 2012-01-18 16:42:49

1

這是由於冒泡/事件傳播。 #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"; 
} 
+0

之內,使用不帶庫的內聯處理程序並不容易。你是指什麼樣的圖書館? jQuery的? – Green 2012-01-17 20:13:55