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

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

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

当前回答

还在寻找检测外部点击的完美解决方案?别再看了!介绍Clickout Event,这是一个为Clickout和其他类似事件提供通用支持的包,它适用于所有场景:普通HTML onclickout属性、普通JavaScript的.addEventListener('clickkout')、jQuery的.on('click kout'”)、Vue.js的v-on:cclickout指令。只要前端框架内部使用addEventListener来处理事件,Clickout Event适用于它。只需在页面中的任何位置添加脚本标记,它就会像魔术一样发挥作用。

HTML属性

<div onclickout="console.log('clickout detected')">...</div>

香草JavaScript

document.getElementById('myId').addEventListener('clickout', myListener);

jQuery

$('#myId').on('clickout', myListener);

Vue.js

<div v-on:clickout="open=false">...</div>

有棱角的

<div (clickout)="close()">...</div>

其他回答

 <div class="feedbackCont" onblur="hidefeedback();">
        <div class="feedbackb" onclick="showfeedback();" ></div>
        <div class="feedbackhide" tabindex="1"> </div>
 </div>

function hidefeedback(){
    $j(".feedbackhide").hide();
}

function showfeedback(){
    $j(".feedbackhide").show();
    $j(".feedbackCont").attr("tabindex",1).focus();
}

这是我想出的最简单的解决方案。

这是一个容器或整个文档中的解决方案。若click目标在元素之外(类为“yourClass”),则元素被隐藏。

$('yourContainer').on('click', function(e) {
  if (!$(e.target).hasClass('yourClass')) {
    $('.yourClass').hide();
  }
});

我有一个应用程序,它的工作方式与Eran的示例类似,只是当我打开菜单时,我会将单击事件附加到主体。。。有点像这样:

$('#menucontainer').click(function(event) {
  $('html').one('click',function() {
    // Hide the menus
  });

  event.stopPropagation();
});

有关jQuery的one()函数的更多信息

对于iPad和iPhone等触摸设备,我们可以使用以下代码:

$(document).on('touchstart', function (event) {
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) &&            // If the target of the click isn't the container...
        container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

投票选出最受欢迎的答案,但添加

&& (e.target != $('html').get(0)) // ignore the scrollbar

因此,单击滚动条不会隐藏目标元素。