javascript 在 DIV 外单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11834657/
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
click outside DIV
提问by Mick Asgorther
<body>
<div id="aaa">
<div id="bbb">
</div>
</div>
</body>
$(#?????).click(function(){
$('#bbb').hide();
})
What i must use if i want hide #bbb if user click outside box #bbb? But if i click on div #bbb then box is still visible - only outside.
如果用户单击框外#bbb,我想隐藏#bbb,我必须使用什么?但是如果我点击 div #bbb 然后框仍然可见 - 只有在外面。
回答by Fresheyeball
$('body').click(function(e){
if( e.target.id == 'bbb' )
{ return true; }
else
{ $('#bbb').hide(); }
});
A note of explanation: There are a few ways to do this, either way we need to listen for a click on a parent element, weather it be a direct parent like #aaa
or a distant parent like the body
or the document
. This way we can capture clicks that occur outside of #bbb
.
记解释:有几个方法可以做到这一点,无论哪种方式,我们需要倾听的父元素上的点击,天气它是一个直接的父母像#aaa
或一个遥远的父母像body
或document
。通过这种方式,我们可以捕获发生在#bbb
.
Now that we have that we need the .hide
to NOT occur if the user did click inside of #bbb
. We can do this two ways
现在我们已经知道,.hide
如果用户确实在#bbb
. 我们可以通过两种方式做到这一点
Stop propagation if the user clicks on
#bbb
. This will make the click event not 'bubble'up to the parent. That way the click event never reaches the parent and so#bbb
will not hide. I personally don't like this method because stop propagation will so ALL click events from bubbling, and you may have click events that you would like to bubble to a local parent and not a distant parent. Or you may have listeners delegated from a distant parent, which will stop working if click propagation is stopped.Check for the
#bbb
element in the parent listener. This is the method shown above. Basically this listens on a distant parent, and when a click occurs it checks to see if that click is on#bbb
specifically. If it IS NOT on#bbb
.hide
is fired, otherwise it returns true, so other things that may be tied into theclick
event will continue working. I prefer this method for that reason alone, but secondarily its a-little bit more readable and understandable.
如果用户单击 ,则停止传播
#bbb
。这将使点击事件不会“冒泡”到父级。这样点击事件永远不会到达父级,因此#bbb
不会隐藏。我个人不喜欢这种方法,因为停止传播会使所有点击事件冒泡,并且您可能有想要冒泡到本地父级而不是远程父级的点击事件。或者,您可能有来自远方的父级委托的侦听器,如果单击传播停止,则该侦听器将停止工作。检查
#bbb
父侦听器中的元素。这是上面显示的方法。基本上,这会侦听远处的父级,当发生点击时,它会检查该点击是否是#bbb
专门开启的。如果它 IS NOT on#bbb
.hide
被触发,否则它返回 true,所以其他可能与click
事件相关的东西将继续工作。仅出于这个原因,我更喜欢这种方法,但其次,它的可读性和可理解性要强一些。
Finally the manner in which you check to see if the click originated at #bbb
you have many options. Any will work, the pattern is the real meat of this thing.
最后,您检查点击是否源于#bbb
您的方式有很多选择。任何都行,模式是这件事的真正核心。
http://jsfiddle.net/tpBq4///Modded from @Raminson who's answer is very similar.
http://jsfiddle.net/tpBq4///修改自@Raminson,他的回答非常相似。
New suggestion, leverage event bubbling without jQuery.
新建议,在没有 jQuery 的情况下利用事件冒泡。
var isOutSide = true
bbb = documment.getElementById('bbb');
document.body.addEventListener('click', function(){
if(!isOutSide){
bbb.style.display = 'none';
}
isOutSide = true;
});
bbb.addEventListener('click', function(){
isOutSide = false;
});
回答by Jasper
Catch the click
event as it bubbles-up to the document
element. When it hits the document
element, hide the element. Then in a click
event handler for the element, stop the propagation of the event so it doesn't reach the document
element:
捕捉click
事件,因为它冒泡到document
元素。当它击中document
元素时,隐藏元素。然后在click
元素的事件处理程序中,停止事件的传播,使其不会到达document
元素:
$(function () {
$(document).on('click', function () {
$('#bbb').hide();
});
$('#bbb').on('click', function (event) {
event.stopPropagation();
});
});
Here is a demo: http://jsfiddle.net/KVXNL/
这是一个演示:http: //jsfiddle.net/KVXNL/
Docs for event.stopPropagation()
: http://api.jquery.com/event.stopPropagation/
文档event.stopPropagation()
:http: //api.jquery.com/event.stopPropagation/
回答by Tyler Crompton
I made a plugin that does this. It preserves the value for this
where as these other solutions' this
value will refer to document
.
我做了一个插件来做到这一点。它保留了this
where的值,因为这些其他解决方案的this
值将引用document
。
https://github.com/tylercrompton/clickOut
https://github.com/tylercrompton/clickOut
Use:
利用:
$('#bbb').clickOut(function () {
$(this).hide();
});
回答by undefined
回答by Simon Edstr?m
This will work
这将工作
$("#aaa").click(function(){
$('#bbb').hide();
});
$("#bbb").click(function(event){
event.stopPropagation();
})?
Becouse bbbis inside the aaathe event will "bubbel up to aaa". So you have to stop the bubbling by using the event.stopPropagation
when bbbis clicked
因为bbb在aaa 内,事件将“冒泡到aaa”。所以,你必须通过停止起泡 event.stopPropagation
时BBB点击
回答by user2011323
OK
行
*this is none jquery. you can easly modify it to work with IE
*这不是 jquery。您可以轻松修改它以与 IE 一起使用
first create helper method to facilitate codding don't get confused with JQuery $()
首先创建辅助方法以促进编码不要与 JQuery $() 混淆
function $g(element) {
return document.getElementById(element);
}
create our listener class
创建我们的监听器类
function globalClickEventListener(obj){
this.fire = function(event){
obj.onOutSideClick(event);
}
}
let's say we need to capture every click on document body
假设我们需要捕获对文档正文的每次点击
so we need to create listeners array and initialize our work. This method will be called on load
所以我们需要创建监听器数组并初始化我们的工作。此方法将在加载时调用
function initialize(){
// $g('body') will return reference to our document body. parameter 'body' is the id of our document body
$g('body').globalClickEventListeners = new Array();
$g('body').addGlobalClickEventListener = function (listener)
{
$g('body').globalClickEventListeners.push(listener);
}
// capture onclick event on document body and inform all listeners
$g('body').onclick = function(event) {
for(var i =0;i < $g('body').globalClickEventListeners.length; i++){
$g('body').globalClickEventListeners[i].fire(event);
}
}
}
after initialization we create event listener and pass reference of the object that needs to know every clcik on our document
初始化后,我们创建事件侦听器并传递需要知道文档中每个 clcik 的对象的引用
function goListening(){
var icanSeeEveryClick = $g('myid');
var lsnr = new globalClickEventListener(icanSeeEveryClick);
// add our listener to listeners array
$g('body').addGlobalClickEventListener(lsnr);
// add event handling method to div
icanSeeEveryClick.onOutSideClick = function (event){
alert('Element with id : ' + event.target.id + ' has been clicked');
}
}
*Take into account the document body height and width
*考虑到文档正文的高度和宽度
*Remove event listeners when you don't need them
*不需要时删除事件侦听器
回答by jroi_web
$(document).click(function(event) {
if(!$(event.target).closest('#elementId').length) {
if($('#elementId').is(":visible")) {
$('#elementId').hide('fast');
}
}
})
Change the "#elementId" with your div.
使用您的 div 更改“#elementId”。