我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
标准HTML:
用<标签>包围菜单并获取焦点状态更改。
http://jsfiddle.net/bK3gL/
另外:您可以通过Tab展开菜单。
其他回答
const button=document.querySelector('button')const box=document.querySelector('.box');常量切换=事件=>{event.stopPropagation();if(!event.target.closest('.box')){console.log('单击外部');box.classList.tggle(“活动”);box.classList.contains('active')? document.addEventListener('click',切换):document.removeEventListener(“单击”,切换);}其他{console.log('单击内部');}}button.addEventListener('单击',切换);.box格式{位置:绝对;显示:无;页边空白:8px;填充:20px;背景:浅灰色;}.box激活{显示:块;}<button>切换框</button><div class=“box”><form action=“”><input-type=“text”><button type=“button”>搜索</button></form></div>
我读过2021的所有内容,但若并没有错的话,也并没有人提出过这样简单的建议,来解除和删除事件。使用了前面的两个答案和更多的小技巧,所以我把所有的都放在了一个里面(它也可以作为一个参数添加到函数中以传递选择器,以获得更多的弹出窗口)。
也许有人知道这个笑话是有用的。也可以这样做:
<div id="container" style="display:none"><h1>my menu is nice, but it disappears if I click outside it</h1></div>
<script>
function printPopup() {
$("#container").css({"display": "block"});
var remListener = $(document).mouseup(function (e) {
if ($(e.target).closest("#container").length === 0 &&
(e.target != $('html').get(0)))
{
//alert('closest call');
$("#container").css({"display": "none"});
remListener.unbind('mouseup'); // Isn't it?
}
});
}
printPopup();
</script>
投票选出最受欢迎的答案,但添加
&& (e.target != $('html').get(0)) // ignore the scrollbar
因此,单击滚动条不会隐藏目标元素。
要隐藏文件TreeClass(如果在其外部单击),请执行以下操作:
jQuery(document).mouseup(function (e) {
var container = $(".fileTreeClass");
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();
}
});
假设您想要检测用户在外部或内部单击的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”方法。