admin管理员组文章数量:1403200
I have a page with a div element in it. i want when i clicked on outer area of that div element, then fade it out.
but i don't know how detect area of mouse click. how detect that mouse click point is out of div area or not??
I have a page with a div element in it. i want when i clicked on outer area of that div element, then fade it out.
but i don't know how detect area of mouse click. how detect that mouse click point is out of div area or not??
Share Improve this question edited Nov 29, 2013 at 3:19 asked Feb 9, 2013 at 14:10 user2057190user2057190 1- 2 possible duplicate of Use jQuery to hide a DIV when the user clicks outside of it. See also stackoverflow./search?q=jquery+click+outside+div – JJJ Commented Feb 9, 2013 at 14:12
3 Answers
Reset to default 3This is not very plicated - you have two options:
1. Asign onclick event to the outer area.
<div id="outer" onclick="$("#inner").fadeOut();">
<div id="inner" onclick="event.cancelBubble=true;/*disable bubling*/">Inner Div</div>
</div>
2. Traverse the dom and pare event.target
(event.srcElement
)
document.addEventListener("click", function(event) {
var body = document.body;
var target = event.target!=null?event.target:event.srcElement;
var inner = document.getElementById("inner");
while(target!=body) {
if(target==inner) //This means our inner element is clicked - or one of its children
return false;
target=target.parentNode; //Go UP in the document tree
}
$("#inner").fadeOut(); //If we got here, none of element matched our inner DIV, so fade it out
}
One possible jQuery solution:
$(document).on("click", function(e) {
var $div = $("#divId");
if (!$div.is(e.target) && !$div.has(e.target).length) {
$div.fadeOut();
}
});
DEMO: http://jsfiddle/5Jb5b/
function clickOn(e) {
var target = e.target;
var optn = [];
optn.id = target.id;
optn.optnClass = target.className.split(' ');
optn.optnType = target.optnName.toLowerCase();
optn.parent = target.parentNode;
return optn;
}
document.body.onclick = function(e) {
elem = clickOn(e);
var option_id = elem.id;
alert( 'option ID: '+option_id); // From id or other properties you can pare and find in which area mouse click occured
};
本文标签: how detect mouse click area in documentjqueryjavascriptStack Overflow
版权声明:本文标题:how detect mouse click area in document - jquery - javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744372016a2603075.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论