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

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

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

当前回答

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

其他回答

这是一个经典的例子,对HTML进行调整将是更好的解决方案。为什么不在不包含菜单项的元素上设置单击?那么您不需要添加传播。

$('.header, .footer, .main-content').click(function() {
//Hide the menus if visible
});
$("body > div:not(#dvid)").click(function (e) {
    //your code
}); 

当只有一个元素需要管理时,这里的解决方案工作得很好。然而,如果有多个元素,问题就复杂得多。e.stopPropagation()的技巧和其他所有技巧都不起作用。

我想出了一个解决方案,也许不是那么容易,但总比什么都没有好。看看:

$view.on("click", function(e) {

    if(model.isActivated()) return;

        var watchUnclick = function() {
            rootView.one("mouseleave", function() {
                $(document).one("click", function() {
                    model.deactivate();
                });
                rootView.one("mouseenter", function() {
                    watchUnclick();
                });
            });
        };
        watchUnclick();
        model.activate();
    });

如果您正在为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;}

检查窗口单击事件目标(它应该传播到窗口,只要它没有在其他地方被捕获),并确保它不是任何菜单元素。如果不是,那么你就在菜单之外。

或者检查单击的位置,看看它是否包含在菜单区域中。