2010-03-29 90 views
2

我點擊按鈕時顯示一個列表,問題是我想在列表失去焦點時隱藏列表,即用戶單擊頁面上的任何位置,但不在列表中。我怎樣才能做到這一點?此外,你可以看到它應該如何看待last.fm,其中的配置文件設置列表(li.profileItem)。 (ul.del li ul默認爲display:none) 基本列表結構:模糊隱藏列表

<ul class='del'> 
    <li> 
     <button class='deletePage'></button> 
     <ul> 
      <li></li> 
      <li></li> 
     </ul> 
    </li> 
</ul> 

我顯示此列表功能:

$(".deletePage").click(function(){ 
    if($(this).siblings(0).css("display") == "block"){ 
     $(this).siblings(0).hide(); 
    } else { 
     $(this).siblings(0).show(); 
    } 
}); 

回答

2

How to detect a click outside an element?

您可以將click處理程序綁定到document到隱藏列表,然後附加一個單獨的處理程序到該按鈕,調用event.stopPropagation

$(document).click(function() { 
$('.list-to-hide').hide(); 
}); 

$('.show-list-button').click(function(event) { 
event.stopPropagation(); 
}); 

或者,你可以使用jQuery outside events plugin

$('.show-list-button').bind('clickoutside', function() { 
$('.list-to-hide').hide(); 
}); 
+0

event.stopPropagation()工作愉快,謝謝! – bah 2010-03-29 20:11:14

1

您可以使用文檔點擊事件。如果用戶在div內部單擊,則事件傳播在此停止(e.stopPropagation),否則將由文檔單擊事件處理,該事件檢查菜單是否打開以及是否關閉菜單。

$(document).click(function() { 
    // check if the menu is open, if so close it 
}); 

$("#windowdiv").click(function(e){ 
    e.stopPropagation(); 
    // do stuff 
});