最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When click anywhere on page, dropdown hide - Stack Overflow

programmeradmin6浏览0评论

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

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; 
});
Share Improve this question asked Nov 9, 2016 at 8:20 eatmailyoeatmailyo 6701 gold badge13 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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()
})

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

Here is the html

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

In your script file

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

Here is the fiddle https://jsfiddle/ej4t2c5u/

发布评论

评论列表(0)

  1. 暂无评论