我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
当只有一个元素需要管理时,这里的解决方案工作得很好。然而,如果有多个元素,问题就复杂得多。e.stopPropagation()的技巧和其他所有技巧都不起作用。
我想出了一个解决方案,也许不是那么容易,但总比什么都没有好。看看:
$view.on("click", function(e) {
if(model.isActivated()) return;
var watchUnclick = function() {
rootView.one("mouseleave", function() {
$(document).one("click", function() {
model.deactivate();
});
rootView.one("mouseenter", function() {
watchUnclick();
});
});
};
watchUnclick();
model.activate();
});
其他回答
只是一个警告,使用这个:
$('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).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);
}
标准HTML:
用<标签>包围菜单并获取焦点状态更改。
http://jsfiddle.net/bK3gL/
另外:您可以通过Tab展开菜单。
现在有一个插件:外部事件(博客文章)
当clickoutside处理程序(WLOG)绑定到元素时,会发生以下情况:
元素被添加到一个数组中,该数组包含所有具有clickoutside处理程序的元素(名称空间)单击处理程序绑定到文档(如果尚未存在)在文档中的任何单击时,都会为该数组中不等于或不是单击事件目标的父级的元素触发单击外部事件此外,clickoutside事件的event.target设置为用户单击的元素(因此您甚至可以知道用户单击了什么,而不仅仅是他在外面单击了什么)
因此,不会阻止任何事件的传播,并且可以在元素的“上方”使用额外的单击处理程序和外部处理程序。
这是我的代码:
// Listen to every click
$('html').click(function(event) {
if ( $('#mypopupmenu').is(':visible') ) {
if (event.target.id != 'click_this_to_show_mypopupmenu') {
$('#mypopupmenu').hide();
}
}
});
// Listen to selector's clicks
$('#click_this_to_show_mypopupmenu').click(function() {
// If the menu is visible, and you clicked the selector again we need to hide
if ( $('#mypopupmenu').is(':visible') {
$('#mypopupmenu').hide();
return true;
}
// Else we need to show the popup menu
$('#mypopupmenu').show();
});