我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
尝试以下代码:
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);
}
其他回答
使用本机JS API最接近方法的2020解决方案。
document.addEventListener('click',({target})=>{if(!target.lestest('#menupop')){document.querySelector('#menupop').style.display=“无”}})#菜单弹出窗口{宽度:300px;高度:300px;背景色:红色;}<div id=“menupop”>单击外部将关闭此</div>
这是我解决问题的方法。
$(window).click(function (event) {
//To improve performance add a checklike
//if(myElement.isClosed) return;
var isClickedElementChildOfMyBox = isChildOfElement(event,'#id-of-my-element');
if (isClickedElementChildOfMyBox)
return;
//your code to hide the element
});
var isChildOfElement = function (event, selector) {
if (event.originalEvent.path) {
return event.originalEvent.path[0].closest(selector) !== null;
}
return event.originalEvent.originalTarget.closest(selector) !== null;
}
您不需要(很多)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>
我很惊讶没有人真正承认这一事件:
var button=document.getElementById('button');button.addEventListener('click',函数(e){e.target.style.backgroundColor=“绿色”;});button.addEventListener('焦点',函数(e){e.target.style.backgroundColor='';});<!DOCTYPE html><html><head><meta charset=“utf-8”></head><body><button id=“button”>单击</button></body></html>
假设您想要检测用户在外部或内部单击的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”方法。