2012-01-10 28 views
21

Estoy tratando de hacerlo para que mi menú desplegable se muestre al hacer clic en un botón y se oculte cuando haga clic en cualquier lugar excepto en el menú desplegable.jQuery ocultar el menú desplegable al hacer clic en cualquier lugar menos en el menú

Tengo algún código en funcionamiento, hasta que no se cierra al hacer clic en el menú; sin embargo, cuando hace clic en el documento cuando el menú está cerrado, muestra el menú, por lo que cambia continuamente sin importar dónde haga clic.

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

Para describir su código; Vincula el evento de clic al documento completo y cuando se activa ese evento, comprueba si el elemento de destino (cliqueado) tiene algún elemento primario con la clase ".notification-container" y, si lo hace, comprueba si hay algún elemento con esa clase es visible. Si es así, oculta (anima) todos los elementos con la clase ".notification-container" y, de lo contrario, los muestra (anima) en su lugar. – Stefan

+0

La mejor solución disponible es [stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element][1]. [1]: http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – lightofsouls

+0

Hey hombre, ¿le importaría aceptar una respuesta? :) – epoch

Respuesta

2

Esto es lo que he decidido usar, es un pequeño plugin jQuery que funciona con poco código.

Aquí está el plugin: http://benalman.com/projects/jquery-outside-events-plugin/

Este es el código que hace que mi código anterior en cuestión mi trabajo.

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

por lo general me gusta esto:

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

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

Así que ponga su cuerpo (en otro lugar), haga clic en la función dentro de la función abierta clic desplegable.

+0

Esto todavía parece hacer lo mismo que mi código actual, curiosamente.Pero gracias –

29

función de jQuery closest() se puede utilizar para ver si el clic no está dentro del menú:

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

No he podido hacer que esto funcione como esperaba, hace lo mismo que hace con mi código actual –

+0

Esto es simple y funciona bien. Es posible que desee considerar agregar el evento click a html en lugar de body en caso de que su página no ocupe todo el alto de la ventana gráfica –

+0

esto funciona genial :) – mshahbazm

1

intentar algo como:

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

Sí, lo he intentado, no funciona en absoluto. –

+0

extraño. si pudieras publicar las partes relevantes de tu código en http://jsfiddle.net/, sería mucho más fácil averiguarlo – redmoon7777

7

se puede hacer algo como esto si su artículo no es hizo clic y luego oculta su lista desplegable en caso de menú desplegable

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

Lo he hecho antes, pero nunca funcionó exactamente bien –

2

Pruebe th es decir:

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

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

esto podría no ser una solución completa, pero he creado un demo para ayudarle a salir. Hazme saber que no está funcionando como esperarías.

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

Parece que funciona como debería en tu demo de violín, gracias. Pero encontré un complemento que funciona perfectamente, con menos código, lo voy a publicar como mi respuesta. –

5

Estoy utilizando un código muy simple para esto: -

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

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

Esperamos que se de utilidad.

Gracias!

Cuestiones relacionadas