Javascript判断鼠标在元素外点击

来源:互联网 发布:淘宝金牌卖家什么意思 编辑:程序博客网 时间:2024/06/06 01:49

 

简单的说:document中mousedown能获得鼠标点击的对象

  IE中用event.srcElement;

  FF中中e.target;

然后遍历判断该对象是否为元素子节点。

<html>
<body>
<input type="button" value="Zswang 路过!" onclick="button_Click()" />
<div id="div_panel" style="display:none;width:200px;height:200px;background-color:Red;">
<a href="http://blog.csdn.net/zswang" alt="广告">http://blog.csdn.net/zswang</a>
<br />
<img src="http://www.csdn.net/Images/logo_csdn.gif" alt="CSDN"/>
</div>
<script type="text/javascript">
function $(id) { return document.getElementById(id); }

function addEventHandler(target, type, func) {
if (target.addEventListener)
target.addEventListener(type, func,
false);
else if (target.attachEvent)
target.attachEvent(
"on" + type, func);
else target["on" + type] = func;
}

function removeEventHandler(target, type, func) {
if (target.removeEventListener)
target.removeEventListener(type, func,
false);
else if (target.detachEvent)
target.detachEvent(
"on" + type, func);
else delete target["on" + type];
}

function button_Click() {
$(
"div_panel").style.display = "";
addEventHandler(document,
"mousedown", document_MouseDown);
}

function document_MouseDown(e) {
var element = typeof event != "undefined" ? event.srcElement : e.target;
var downPanel = false;
while (element) {
downPanel
= element == $("div_panel");
if (downPanel) break;
element
= element.parentNode;
}
if (!downPanel) {
removeEventHandler(document,
"mousedown", document_MouseDown);
$(
"div_panel").style.display = "none";
}
}
</script>
</body>
</html>
原创粉丝点击