我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。

jQuery是否可以实现这样的功能?

$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});

当前回答

这是面向未来观众的普通JavaScript解决方案。

单击文档中的任何元素时,如果已切换所单击元素的id,或者隐藏元素未隐藏且隐藏元素不包含所单击元素,则切换该元素。

(function () {
    "use strict";
    var hidden = document.getElementById('hidden');
    document.addEventListener('click', function (e) {
        if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';
    }, false);
})();

(函数(){“使用严格”;var hidden=document.getElementById('hidden');document.addEventListener('click',函数(e){如果(e.target.id==“toggle”| |(hidden.style.display!=“none”&&!hidden.concloss(e.target)))hidden.syle.display=hidden.sstyle.display==“none?”block':'无';},假);})();<a href=“javascript:void(0)”id=“toggle”>切换隐藏潜水</a><div id=“hidden”style=“display:none;”>此内容通常是隐藏的。单击此内容以外的任何位置,使我消失</div>

如果您要在同一页面上进行多个切换,可以使用以下方式:

将隐藏的类名添加到可折叠项中。单击文档后,关闭所有不包含所单击元素且未隐藏的隐藏元素如果单击的元素是切换,请切换指定的元素。

(函数(){“使用严格”;var hiddenItems=document.getElementsByClassName('hidden'),隐藏;document.addEventListener('click',函数(e){for(var i=0;hidden=hiddenItems[i];i++){如果(!hidden.contains(e.target)&&hidden.style.display!='无”)hidden.style.display=“无”;}if(e.target.getAttribute('data-toggle')){var toggle=document.querySelector(e.target.getAttribute('data-toggle'));toggle.style.display=toggle.style.display==“无”?'block':'无';}},假);})();<a href=“javascript:void(0)”data toggle=“#hidden1”>切换隐藏潜水</a><div class=“hidden”id=“hidden1”style=“display:none;”data hidden=“true”>此内容通常隐藏</div><a href=“javascript:void(0)”data toggle=“#hidden2”>切换隐藏潜水</a><div class=“hidden”id=“hidden2”style=“display:none;”data hidden=“true”>此内容通常隐藏</div><a href=“javascript:void(0)”data toggle=“#hidden3”>切换隐藏潜水</a><div class=“hidden”id=“hidden3”style=“display:none;”data hidden=“true”>此内容通常隐藏</div>

其他回答

这对我来说很好。我不是专家。

$(document).click(function(event) {
  var $target = $(event.target);
  if(!$target.closest('#hamburger, a').length &&
  $('#hamburger, a').is(":visible")) {
    $('nav').slideToggle();
  }
});

简单插件:

$.fn.clickOff = function(callback, selfDestroy) {
    var clicked = false;
    var parent = this;
    var destroy = selfDestroy || true;

    parent.click(function() {
        clicked = true;
    });

    $(document).click(function(event) {
        if (!clicked && parent.is(':visible')) {
            if(callback) callback.call(parent, event)
        }
        if (destroy) {
            //parent.clickOff = function() {};
            //parent.off("click");
            //$(document).off("click");
            parent.off("clickOff");
        }
        clicked = false;
    });
};

Use:

$("#myDiv").clickOff(function() {
   alert('clickOff');
});
$(document).on('click.menu.hide', function(e){
  if ( !$(e.target).closest('#my_menu').length ) {
    $('#my_menu').find('ul').toggleClass('active', false);
  }
});

$(document).on('click.menu.show', '#my_menu li', function(e){
  $(this).find('ul').toggleClass('active');
});
div {
  float: left;
}

ul {
  padding: 0;
  position: relative;
}
ul li {
  padding: 5px 25px 5px 10px;
  border: 1px solid silver;
  cursor: pointer;
  list-style: none;
  margin-top: -1px;
  white-space: nowrap;
}
ul li ul:before {
  margin-right: -20px;
  position: absolute;
  top: -17px;
  right: 0;
  content: "\25BC";
}
ul li ul li {
  visibility: hidden;
  height: 0;
  padding-top: 0;
  padding-bottom: 0;
  border-width: 0 0 1px 0;
}
ul li ul li:last-child {
  border: none;
}
ul li ul.active:before {
  content: "\25B2";
}
ul li ul.active li {
  display: list-item;
  visibility: visible;
  height: inherit;
  padding: 5px 25px 5px 10px;
}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<div>
  <ul id="my_menu">
    <li>Menu 1
      <ul>
        <li>subMenu 1</li>
        <li>subMenu 2</li>
        <li>subMenu 3</li>
        <li>subMenu 4</li>
      </ul>
    </li>
    <li>Menu 2
      <ul>
        <li>subMenu 1</li>
        <li>subMenu 2</li>
        <li>subMenu 3</li>
        <li>subMenu 4</li>
      </ul>
    </li>
    <li>Menu 3</li>
    <li>Menu 4</li>
    <li>Menu 5</li>
    <li>Menu 6</li>
  </ul>
</div>

这里是jsbin版本http://jsbin.com/xopacadeni/edit?html,css,js,输出

外部点击插件!

用法:

$('.target-element').outsideClick(function(event){
    //code that fires when user clicks outside the element
    //event = the click event
    //$(this) = the '.target-element' that is firing this function 
}, '.excluded-element')

它的代码:

(function($) {

//when the user hits the escape key, it will trigger all outsideClick functions
$(document).on("keyup", function (e) {
    if (e.which == 27) $('body').click(); //escape key
});

//The actual plugin
$.fn.outsideClick = function(callback, exclusions) {
    var subject = this;

    //test if exclusions have been set
    var hasExclusions = typeof exclusions !== 'undefined';

    //switches click event with touch event if on a touch device
    var ClickOrTouchEvent = "ontouchend" in document ? "touchend" : "click";

    $('body').on(ClickOrTouchEvent, function(event) {
        //click target does not contain subject as a parent
        var clickedOutside = !$(event.target).closest(subject).length;

        //click target was on one of the excluded elements
        var clickedExclusion = $(event.target).closest(exclusions).length;

        var testSuccessful;

        if (hasExclusions) {
            testSuccessful = clickedOutside && !clickedExclusion;
        } else {
            testSuccessful = clickedOutside;
        }

        if(testSuccessful) {
            callback.call(subject, event);
        }
    });

    return this;
};

}(jQuery));

根据此答案改编https://stackoverflow.com/a/3028037/1611058

使用not():

$("#id").not().click(function() {
    alert('Clicked other that #id');
});