2011-07-19 45 views
4

我正在嘗試使面板在按鈕上單擊時打開。我有按鈕,我有面板。與click()事件它確實打開。當再次按下該按鈕時,它確實關閉。如何在除了打開的元素之外的任何位置點擊時關閉元素?

$('#button').click(function() { 

    $('#panel').toggle(); 
}); 

我要實現,如果用戶點擊無處不在除了在#button#panel,它接近了。

P.S.我嘗試過這樣的事情,但這不是想要的行爲。

$('#button').mouseenter(function() { 

    $('#panel').show(); 

}).mouseleave(function() { 

    setTimeout(function() { 
     $('#panel').hide(); 
    }, 2000); 
}); 

回答

4
$(
    function(){ 
     $("#button").click(function(){ $("#panel").toggle(); }); 
     $(document).click(function(e){ 
      var elm = jQuery(e.target); 
      if(elm.is("#button") || elm.is("#panel") || elm.parents("#panel").length>0)return; 
      $("#panel").hide(); 
     }); 
    } 
); 

Example什麼

檢查,以確保被點擊[e.target]該元素不是

  1. 按鈕elm.is("#button")
  2. 面板elm.is("#panel")
  3. 在面板elm.parents("#panel").length>0
+0

你可以停止按鈕和麪板點擊傳播的方式,你不必明確檢查按鈕和麪板。 – ShankarSangoli

+0

謝謝!^__ ^真棒..... – daGrevis

3

嘗試此

$('#button').click(function(e) { 

    $('#panel').toggle(); 
    e.stopPropagation(); 

}); 

$('#panel').click(function(e) { 

    e.stopPropagation(); 

}); 

$(document.body).click(function(e) { 
    if($('#panel').is(":visible")){ 
     $('#panel').hide(); 
    } 
}); 
0

具有分層的面板,這會佔用100%的屏幕(或頁)的後面的不可見元素。這個元素將被賦予可以關閉任何面板的click事件。

這也可以防止點擊關閉面板觸發對網站其他部分的任何其他操作。

如果你想,你也可以使分層元素變成灰色和半透明的,這會給你在顯示面板時重影網站其他部分的效果。這種效果通常由Javascript彈出框腳本使用,並且您可以通過虛擬方式免費使用它,因爲您已經放置了全屏元素;你只需要設計它。

1

直接回答你的要求會

$('body').click(function(e) 

    var starter = $(e.target); 
    if (starter.is('#button, #panel') || starter.closest('#panel').length > 0) return; 

    setTimeout(function() { 
     $('#panel').hide(); 
    }, 2000); 

}) 

但看到你嘗試與鼠標移開做你可能會認爲這是一個更好的辦法

$('#button').click(function() { 

    $('#panel').show(); 

}); 

$('#panel').mousenter(function() { 

    var closetimer = $(this).data('closetimer'); // retrieve the timer if it exists 
    clearTimeout(closetimer); // and clear the timeout when we re-enter to cancel the closing 

}).mouseleave(function() { 

    var closetimer = setTimeout(function() { 
     $('#panel').hide(); 
    }, 2000); 

    $(this).data('closetimer', closetimer); // store the timer with the panel so we can cancel it if we need 

}); 
+1

失敗的任何元素,如果有內容在面板內部。 – epascarello

+0

@epascarello,確實它會失敗的面板內的標籤..修正.. –

相關問題