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

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

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

当前回答

外部点击插件!

用法:

$('.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

其他回答

如果有人好奇这里是javascript解决方案(es6):

window.addEventListener('mouseup', e => {
        if (e.target != yourDiv && e.target.parentNode != yourDiv) {
            yourDiv.classList.remove('show-menu');
            //or yourDiv.style.display = 'none';
        }
    })

和es5,以防万一:

window.addEventListener('mouseup', function (e) {
if (e.target != yourDiv && e.target.parentNode != yourDiv) {
    yourDiv.classList.remove('show-menu'); 
    //or yourDiv.style.display = 'none';
}

});

假设您想要检测用户在外部或内部单击的div是否具有id,例如:“我的特殊小部件”。

收听身体点击事件:

document.body.addEventListener('click', (e) => {
    if (isInsideMySpecialWidget(e.target, "my-special-widget")) {
        console.log("user clicked INSIDE the widget");
    }
    console.log("user clicked OUTSIDE the widget");
});

function isInsideMySpecialWidget(elem, mySpecialWidgetId){
    while (elem.parentElement) {
        if (elem.id === mySpecialWidgetId) {
            return true;
        }
        elem = elem.parentElement;
    }
    return false;
}

在这种情况下,您不会破坏页面中某些元素的正常点击流,因为您没有使用“stopPropagation”方法。

您不需要(很多)JavaScript,只需要选择器内的:focus:

使用侧边栏:集中在显示侧边栏。在侧边栏和正文元素上设置tabindex=-1,使其可聚焦。使用sidbarEl.focus()和document.body.focus)设置侧边栏的可见性。

const menuButton=document.querySelector('.menu button');const sidebard=document.querySelector('.sidebard');menuButton.onmousedown=ev=>{ev.prpreventDefault();(边栏.包含(document.activeElement)?document.body:侧边栏).focus();};*{框大小调整:边框;}.侧边栏{位置:固定;宽度:15em;左:-15em;顶部:0;底部:0;过渡:左0.3s缓进缓出;背景色:#eef;衬垫:3em 1em;}侧边栏:焦点在{左:0;}.侧边栏:焦点{大纲:0;}.菜单按钮{位置:固定;顶部:0;左:0;填充:1em;背景色:#eef;边框:0;}正文{最大宽度:30em;边距:3em;}<body tabindex='-1'><nav class='sidebar'tabindex='-1'>提要栏内容<input-type=“text”/></nav><button class=“菜单按钮”>☰</按钮>身体内容在这里,Lorem ipsum坐amet等</body>

$("body > div:not(#dvid)").click(function (e) {
    //your code
}); 

$('html').click(function(){//隐藏菜单(如果可见)});$('#menucontainer').click(函数(事件){event.stopPropagation();});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><html><button id=“#menucontainer”>确定</button></html>