Подтвердить что ты не робот

JQuery скрыть выпадающее меню при нажатии, но меню

Я пытаюсь сделать так, чтобы мое раскрывающееся меню показывалось, когда вы нажимаете кнопку, и скрывается, когда вы нажимаете где-либо, кроме раскрывающегося меню.

У меня есть какой-то код, который не закрывается, когда вы нажимаете меню, однако, когда вы нажимаете на документ, когда меню закрыто, оно отображает меню, поэтому оно непрерывно переключается независимо от того, где вы нажимаете.

$(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);
        }
    }
});
4b9b3361

Ответ 1

Это то, что я решил использовать, это хороший плагин 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)});
    });
});

Ответ 2

jQuery closeest() может использоваться, чтобы увидеть, нет ли щелчка в меню:

$('body').click(function(e) {
    if ($(e.target).closest('.notification-container').length === 0) {
        // close/animate your div
    }
});

Ответ 3

вы можете сделать что-то вроде этого, если ваш элемент не щелкнут, а затем скройте его выпадающий список в случае выпадающего списка

$(':not(#country)').click(function() {
     $('#countrylist').hide();
});

Ответ 4

Я использую для этого простой код: -

$(document).click(function(e){

   if($(e.target).closest('#dropdownID').length != 0) return false;
   $('#dropdownID').hide();
});

Надеюсь, что это будет полезно.

Спасибо!!

Ответ 5

Я обычно делаю так:

$('.drop-down').click(function () {
    // The code to open the dropdown

    $('body').click(function () {
        // The code to close the dropdown
    });
});

Итак, разместите свое тело (в другом месте), щелкнув функцию внутри раскрывающейся кнопки щелчка.

Ответ 6

Попробуйте следующее:

// The code to close the dropdown
$(document).click(function() {
    ...
});

// The code to open the dropdown 
$(".drop-down").click(function() {
    ...
    return false;
});

Ответ 7

Это может быть не полное решение, но я создал demo, чтобы помочь вам. Позвольте мне знать, что он не работает так, как вы ожидали.

$(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);
});

Ответ 8

попробуйте что-то вроде:

$(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);
});