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

javascript - How to close bootstrap 3 dropdown when we click outside on a tablet? - Stack Overflow

programmeradmin4浏览0评论

I am doing this and it works fine on the desk:

$(document).on("click", function(){
  $(".dropdown-toggle").removeClass("open");
});

But on the iPad that it isn't working and my dropdown remains open

I am doing this and it works fine on the desk:

$(document).on("click", function(){
  $(".dropdown-toggle").removeClass("open");
});

But on the iPad that it isn't working and my dropdown remains open

Share Improve this question asked Jan 29, 2015 at 14:56 rob.mrob.m 10.6k21 gold badges88 silver badges175 bronze badges 1
  • Mobile Safari doesn't fire click events unless it deems the element to be clickable; see developer.mozilla/en-US/docs/Web/Events/click#Safari_Mobile – cvrebert Commented Jan 29, 2015 at 16:36
Add a ment  | 

3 Answers 3

Reset to default 4

You should use the touchstart and touchend events with touch devices:

$(document).on("click touchend", function(){
    $(".dropdown-toggle").removeClass("open");
});

This answer relates to navbar menus, rather than general dropdowns, but I came across this while looking for the answer to my own similar question (close hamburger menus when tapping outside), so thought I'd post an alternative solution for anyone else, as the accepted answer does not work with hamburger submenus (tapping to open a submenu would close the hamburger menu).

This answer was based on the accepted answer and this answer, as well as NickGreen's ment on this answer.

$('html').on('click, touchend', function (e) {
    // Close hamburger menu when tapping outside
    if ($(e.target).closest('.navbar').length == 0) {
        var opened = $('.navbar-collapse').hasClass('collapse in');
        if (opened === true) {
            $('.navbar-collapse').collapse('hide');
        }
    }
});

I use this snippet if I don't want to close any dropdown on the page when the user clicks inside it.

$(document).on('click touchend', function(e) {
  if ($(e.target).closest('.open').length === 0) {
    $('.dropdown-toggle').parent().removeClass('open');
  }
});
发布评论

评论列表(0)

  1. 暂无评论