我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
$("#menuscontainer").click(function() {
$(this).focus();
});
$("#menuscontainer").blur(function(){
$(this).hide();
});
对我来说很好。
其他回答
只是一个警告,使用这个:
$('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();
}
});
老实说,我不喜欢以前的任何解决方案。
要做到这一点,最好的方法是将“点击”事件绑定到文档,并比较该点击是否真的在元素之外(就像Art在建议中所说的那样)。
然而,您会遇到一些问题:您永远无法解除绑定,并且无法使用外部按钮打开/关闭该元素。
这就是为什么我编写了这个小插件(点击此处链接),以简化这些任务。能简单一点吗?
<a id='theButton' href="#">Toggle the menu</a><br/>
<div id='theMenu'>
I should be toggled when the above menu is clicked,
and hidden when user clicks outside.
</div>
<script>
$('#theButton').click(function(){
$('#theMenu').slideDown();
});
$("#theMenu").dClickOutside({ ignoreList: $("#theButton") }, function(clickedObj){
$(this).slideUp();
});
</script>
使用not():
$("#id").not().click(function() {
alert('Clicked other that #id');
});
我有一个应用程序,它的工作方式与Eran的示例类似,只是当我打开菜单时,我会将单击事件附加到主体。。。有点像这样:
$('#menucontainer').click(function(event) {
$('html').one('click',function() {
// Hide the menus
});
event.stopPropagation();
});
有关jQuery的one()函数的更多信息
作为Art这个伟大答案的包装,并使用OP最初要求的语法,这里有一个jQuery扩展,它可以记录在集合元素之外是否发生了单击。
$.fn.clickOutsideThisElement = function (callback) {
return this.each(function () {
var self = this;
$(document).click(function (e) {
if (!$(e.target).closest(self).length) {
callback.call(self, e)
}
})
});
};
然后你可以这样打电话:
$("#menuscontainer").clickOutsideThisElement(function() {
// handle menu toggle
});
这是小提琴演示