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()。如果“详细信息”元素可见,我希望按钮单击以保持加号,对屏幕的其他部分做出反应。
$('.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');
}
});
});
2 个解决方案
#1
25
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
检查FIDDLE
I did not understand what you meant by integrating with the other part.. This is the basic idea..
通过与其他部分的整合,我不明白你的意思..这是基本的想法..
#2
3
You can use the jQuery .blur()
function to hide a div when user click on other element (like link, boutton, whathever..)
你可以使用jQuery .blur()函数在用户点击其他元素时隐藏div(比如link,boutton,whathever ..)
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,它的内部切换功能你应该在div上放置hide()/ show(),同时更新按钮的文本。
#1
25
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
检查FIDDLE
I did not understand what you meant by integrating with the other part.. This is the basic idea..
通过与其他部分的整合,我不明白你的意思..这是基本的想法..
#2
3
You can use the jQuery .blur()
function to hide a div when user click on other element (like link, boutton, whathever..)
你可以使用jQuery .blur()函数在用户点击其他元素时隐藏div(比如link,boutton,whathever ..)
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,它的内部切换功能你应该在div上放置hide()/ show(),同时更新按钮的文本。