我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
Use:
var go = false;
$(document).click(function(){
if(go){
$('#divID').hide();
go = false;
}
})
$("#divID").mouseover(function(){
go = false;
});
$("#divID").mouseout(function (){
go = true;
});
$("btnID").click( function(){
if($("#divID:visible").length==1)
$("#divID").hide(); // Toggle
$("#divID").show();
});
其他回答
$('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>
作为一种变体:
var $menu = $('#menucontainer');
$(document).on('click', function (e) {
// If element is opened and click target is outside it, hide it
if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {
$menu.hide();
}
});
它在停止事件传播方面没有问题,并且更好地支持同一页面上的多个菜单,其中当第一个菜单打开时,单击第二个菜单将使stopPropagation解决方案中的第一个菜单保持打开状态。
要做到这一点,最广泛的方法是选择网页上的所有内容,除了不希望检测到点击的元素,并在打开菜单时绑定点击事件。
然后,当菜单关闭时,移除绑定。
使用.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();
});
您不需要(很多)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
});