When click anywhere on page, dropdown hide

时间:2016-11-09 08:20:39

标签: javascript jquery html css

Im searched a lot about my problem, but didnt find any solution. I know, Im new in JavaScript/JQuery, but maybe some one can help me :) I made this nice dropdown, what was working just, how I need, but there is the last bug. When I click anywhere on page, it doesn't hide. There's my JSFiddle

Any solutions there?

There's my JavaScript/JQuery

var $dropdown = $('.dropdown-content');

$(".dropdown-label").click(function(e){
    var $drop = $(this).toggleClass('dropdown--active').find(".dropdown-content").stop(true).toggle(100);
    $dropdown.not($drop).stop(true).hide(100);
    return false; 
});

4 个答案:

答案 0 :(得分:6)

In the code below I added only the document click binding.

var $dropdown = $('.dropdown-content');

$(".dropdown-label").click(function(e){
    var $drop = $(this).toggleClass('dropdown--active').find(".dropdown-content").stop(true).toggle(100);
    $dropdown.not($drop).stop(true).hide(100);
    return false; 
});

$(document).on("click", function() {
    $(".dropdown-content").hide()
})

答案 1 :(得分:3)

updated fiddle click with document .It will hide the .dropdown-content .And apply e.preventDefault() they prevent from other click

$(document).click(function(e){
$(".dropdown-content").hide();
e.preventDefault();
})

答案 2 :(得分:1)

这是html

 <div class="dropdown-content" style="width: 200px;height: 200px;border:1px solid #ccc;"></div>

在您的脚本文件中

  $(document).on("click","body",function(e) { 
        if(!$(e.target).hasClass("dropdown-content")) { 
          $(".dropdown-content").hide(); 
        }
  });

这是小提琴https://jsfiddle.net/ej4t2c5u/

答案 3 :(得分:1)

.dropdown-content将其更改为id,我认为这是一个很好而简单的解决方案

window.addEventListener('mouseup',function(){


var popup =document.getElementById('dropdown-content');



if (event.target != popup && event.target.parentNode != popup) 

{

popup.style.display='none';


}






});