我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
只是一个警告,使用这个:
$('html').click(function() {
// Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
它阻止RubyonRails UJS驱动程序正常工作。例如,link_to“click”、“/url”、:method=>:delete将不起作用。
这可能是一种变通方法:
$('html').click(function() {
// Hide the menus if visible
});
$('#menucontainer').click(function(event){
if (!$(event.target).data('method')) {
event.stopPropagation();
}
});
其他回答
这里的其他解决方案不适合我,所以我不得不使用:
if(!$(event.target).is('#foo'))
{
// hide menu
}
编辑:普通Javascript变体(2021-03-31)
我使用这个方法来处理在单击下拉菜单外部时关闭下拉菜单的问题。
首先,我为组件的所有元素创建了一个自定义类名。这个类名将被添加到组成菜单小部件的所有元素中。
const className = `dropdown-${Date.now()}-${Math.random() * 100}`;
我创建了一个函数来检查单击和单击元素的类名。如果clicked元素不包含我上面生成的自定义类名,它应该将show标志设置为false,菜单将关闭。
const onClickOutside = (e) => {
if (!e.target.className.includes(className)) {
show = false;
}
};
然后,我将单击处理程序附加到窗口对象。
// add when widget loads
window.addEventListener("click", onClickOutside);
……最后还有一些家政服务
// remove listener when destroying the widget
window.removeEventListener("click", onClickOutside);
我有一个应用程序,它的工作方式与Eran的示例类似,只是当我打开菜单时,我会将单击事件附加到主体。。。有点像这样:
$('#menucontainer').click(function(event) {
$('html').one('click',function() {
// Hide the menus
});
event.stopPropagation();
});
有关jQuery的one()函数的更多信息
这是一个经典的例子,对HTML进行调整将是更好的解决方案。为什么不在不包含菜单项的元素上设置单击?那么您不需要添加传播。
$('.header, .footer, .main-content').click(function() {
//Hide the menus if visible
});
要做到这一点,最广泛的方法是选择网页上的所有内容,除了不希望检测到点击的元素,并在打开菜单时绑定点击事件。
然后,当菜单关闭时,移除绑定。
使用.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();
});
$('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>