[英]jQuery hide dropdown when clicked anywhere but menu
我正在嘗試將其設置為當您單擊按鈕時顯示我的下拉菜單,並且當您單擊除下拉菜單之外的任何位置時隱藏該隱藏菜單。
我有一些代碼正常工作,當你單擊菜單時沒有關閉,但是當你關閉菜單時單擊文檔,它會顯示菜單,所以無論你在哪里點擊它都會不斷切換。
$(document).click(function(event) {
if ($(event.target).parents().index($('.notification-container')) == -1) {
if ($('.notification-container').is(":visible")) {
$('.notification-container').animate({
"margin-top": "-15px"
}, 75, function() {
$(this).fadeOut(75)
});
} else {
//This should only show when you click: ".notification-button" not document
$('.notification-container').show().animate({
"margin-top": "0px"
}, 75);
}
}
});
jQuery的nearest()函數可用於查看單擊是否不在菜單中:
$('body').click(function(e) {
if ($(e.target).closest('.notification-container').length === 0) {
// close/animate your div
}
});
如果沒有點擊你的項目,你可以做這樣的事情,然后在下拉的情況下隱藏它的刪除列表
$(':not(#country)').click(function() {
$('#countrylist').hide();
});
我正在使用一個非常簡單的代碼: -
$(document).click(function(e){
if($(e.target).closest('#dropdownID').length != 0) return false;
$('#dropdownID').hide();
});
希望它會有用。
謝謝!!
我通常喜歡這樣:
$('.drop-down').click(function () {
// The code to open the dropdown
$('body').click(function () {
// The code to close the dropdown
});
});
所以把你的身體(其他地方)點擊功能放在下拉打開點擊功能中。
試試這個 :
// The code to close the dropdown
$(document).click(function() {
...
});
// The code to open the dropdown
$(".drop-down").click(function() {
...
return false;
});
這可能不是一個完整的解決方案,但我已經創建了一個演示來幫助您。 讓我知道它沒有像你期望的那樣工作。
$(document).click(function(e) {
var isModalBox = (e.target.className == 'modal-box');
if (!isModalBox) {
$('.modal-box:visible').animate({
"margin-top": "-15px"
}, 75, function() {
$(this).fadeOut(75);
});
}
});
$('a').click(function(e) {
e.stopPropagation(); // Important if you´d like other links to work as usual.
});
$('#temp-button').click(function(e) {
e.preventDefault();
$('.modal-box').show().animate({
"margin-top": "0px"
}, 75);
});
嘗試類似的東西:
$(document).click(function(event) {
if($(event.target).parents().index($('.notification-container')) == -1) {
if($('.notification-container').is(":visible")) {
$('.notification-container').animate({"margin-top":"-15px"}, 75, function({$(this).fadeOut(75)});
}
}
});
$(".notification-button").click(function(event){
event.stopPropagation();
$('.notification-container').show().animate({"margin-top":"0px"}, 75);
});
這是我決定使用的,它是一個很好的小jQuery插件,可以使用很少的代碼。
這是插件: http : //benalman.com/projects/jquery-outside-events-plugin/
這是在我的問題中使我的上述代碼工作的代碼。
$(document).ready(function(){
$(".notification-button").click(function(){
$('.notification-container').toggle().animate({"margin-top":"0px"}, 75);
});
$('.notification-wrapper').bind('clickoutside', function (event) {
$('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.