我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
投票选出最受欢迎的答案,但添加
&& (e.target != $('html').get(0)) // ignore the scrollbar
因此,单击滚动条不会隐藏目标元素。
其他回答
$('#menucontainer').click(function(e){
e.stopPropagation();
});
$(document).on('click', function(e){
// code
});
我读过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>
我已经使用了下面的脚本并完成了jQuery。
jQuery(document).click(function(e) {
var target = e.target; //target div recorded
if (!jQuery(target).is('#tobehide') ) {
jQuery(this).fadeOut(); //if the click element is not the above id will hide
}
})
下面是HTML代码
<div class="main-container">
<div> Hello I am the title</div>
<div class="tobehide">I will hide when you click outside of me</div>
</div>
你可以在这里阅读教程
我很惊讶没有人真正承认这一事件:
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>
这种情况的简单解决方案是:
$(document).mouseup(function (e)
{
var container = $("YOUR SELECTOR"); // Give you class or ID
if (!container.is(e.target) && // If the target of the click is not the desired div or section
container.has(e.target).length === 0) // ... nor a descendant-child of the container
{
container.hide();
}
});
如果在div单击事件之外触发,上述脚本将隐藏div。