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

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

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

当前回答

如果您正在使用“弹出窗口”等工具,则可以使用“onFocusOut”事件。

window.onload=函数(){document.getElementById(“内部div”).focus();}函数loseFocus(){警报(“在外面单击”);}#集装箱{背景色:浅蓝色;宽度:200px;高度:200px;}#内部div{背景色:浅灰色;宽度:100px;高度:100px;}<div id=“container”><input type=“text”id=“inside div”onfocusout=“loseFocus()”></div>

其他回答

试试这个:

$('html').click(function(e) {
  if($(e.target).parents('#menuscontainer').length == 0) {
    $('#menuscontainer').hide();
  }
});

https://jsfiddle.net/4cj4jxy0/

但请注意,如果单击事件无法到达html标记,则这将无法工作。(可能其他元素已停止传播())。

如果您正在为IE和FF 3.*编写脚本,并且您只想知道单击是否发生在某个框区域内,您也可以使用以下内容:

this.outsideElementClick=函数(objEvent,objElement){var objCurrentElement=objEvent.target | | objEvent.srcElement;var blnSideX=false;var blnSideY=false;如果(objCurrentElement.getBoundingClientRect().left>=objElement.getBoundingClientRect().left&&objCurrentElement.getBoundingClientRectblnSideX=真;如果(objCurrentElement.getBoundingClientRect().top>=objElement.getBoundingClientRect().ttop&&objCurrentElement.getBoundingClientRectblnSideY=真;如果(blnSideX&&blnSideY)return false;其他的返回true;}

要做到这一点,最广泛的方法是选择网页上的所有内容,除了不希望检测到点击的元素,并在打开菜单时绑定点击事件。

然后,当菜单关闭时,移除绑定。

使用.stopPropagation可防止事件影响菜单容器的任何部分。

$("*").not($("#menuscontainer")).bind("click.OutsideMenus", function ()
{
    // hide the menus

    //then remove all of the handlers
    $("*").unbind(".OutsideMenus");
});

$("#menuscontainer").bind("click.OutsideMenus", function (event) 
{
    event.stopPropagation(); 
});

尝试以下代码:

if ($(event.target).parents().index($('#searchFormEdit')) == -1 &&
    $(event.target).parents().index($('.DynarchCalendar-topCont')) == -1 &&
    (_x < os.left || _x > (os.left + 570) || _y < os.top || _y > (os.top + 155)) &&
    isShowEditForm) {

    setVisibleEditForm(false);
}

只是一个警告,使用这个:

$('html').click(function() {
  // Hide the menus if visible
});

$('#menucontainer').click(function(event){
  event.stopPropagation();
});

它阻止RubyonRails UJS驱动程序正常工作。例如,link_to“click”、“/url”、:method=>:delete将不起作用。

这可能是一种变通方法:

$('html').click(function() {
  // Hide the menus if visible
});

$('#menucontainer').click(function(event){
  if (!$(event.target).data('method')) {
    event.stopPropagation();
  }
});