Javascript jQuery:单击元素之外的任何其他地方时隐藏元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12720495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Hide element on click anywhere else apart of the element
提问by crs1138
Possible Duplicate:
How to detect a click outside an element?
可能的重复:
如何检测元素外的点击?
I'm trying to achieve that a div
hides if user clicks anywhere except on the element. I've got following code doing toggle()
if user clicks on a button. I want the button click to stay plus if the Details
element is visible, reacts to other parts of the screen.
我试图实现div
隐藏,如果用户点击除了元素上的任何地方。toggle()
如果用户单击按钮,我会执行以下代码。如果Details
元素可见,我希望按钮点击保持加号,对屏幕的其他部分做出反应。
$('.nav-toggle').click(function() {
//get collapse content selector
var collapse_content_selector = $(this).attr('href');
//make the collapse content to be shown or hide
var toggle_switch = $(this);
$(collapse_content_selector).toggle(function() {
if ($(this).css('display') == 'none') {
//change the button label to be 'Show'
toggle_switch.html('Show Details');
} else {
//change the button label to be 'Hide'
toggle_switch.html('Hide Details');
}
});
});
采纳答案by Sushanth --
You can resort to the concept of event delegation.
您可以求助于事件委托的概念。
$(function() {
$(document).on('click', function(e) {
if (e.target.id === 'div1') {
alert('Div Clicked !!');
} else {
$('#div1').hide();
}
})
});?
Check FIDDLE
检查小提琴
I did not understand what you meant by integrating with the other part.. This is the basic idea..
我不明白你所说的与另一部分集成是什么意思..这是基本思想..
回答by MatRt
You can use the jQuery .blur()
function to hide a div when user click on other element (like link, boutton, whathever..)
jQuery .blur()
当用户单击其他元素(如链接、按钮等)时,您可以使用该函数隐藏 div
The blur event is fire when an element is loosing the focus (user select another element on the DOM tree)
当元素失去焦点(用户选择 DOM 树上的另一个元素)时会触发模糊事件
I don't understand the link with your toggle. If your toggle button manage the DIV, its inside the toggle function that you should place the hide()/show() on the div, in the same time as updating the text of the button.
我不明白你的切换链接。如果您的切换按钮管理 DIV,则它在切换功能内,您应该将 hide()/show() 放在 div 上,同时更新按钮的文本。