function test(evt){ if(!$('div1')||$('div1').style.display=='none'){ return; } var e = window.event || e; var o = e.srcElement || e.target; while (o) { if (o == $("div1")) { return; } o = o.parentNode; } // alert("hi! you should close the div1!") $('div1').style.display='none'; }
(1) 在onblur事件中判断一下 toElement (FF下是 relatedTarget)是不是在DIV中,
如果不是则关闭DIV。IE下有一上函数 obj.contains();可以用来进行判断。
不多说了,这个有很多的例子可以参考。(2)如果只是IE下的话,还可以用createPopup()
当弹出窗口失去焦点的时候系统会自动关闭弹出窗口。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<style>
</style>
</head>
<script language="JavaScript">
function $(id){
return (document.getElementById(id));
}
function test(evt){
if(!$('div1')||$('div1').style.display=='none'){
return;
}
var e = window.event || e;
var o = e.srcElement || e.target;
while (o) {
if (o == $("div1")) {
return;
}
o = o.parentNode;
}
// alert("hi! you should close the div1!")
$('div1').style.display='none';
}
window.onload = function(){
document.onblur = document.onmousedown = document.onkeyup = test;
}
</script>
<body>
<input type="button" value="show div" onclick="$('div1').style.display='block';"><br>
<input type="text" value=""><br>
<input type="text" value=""><br>
<div id="div1" align="center" style="background:blue;position:absolute;left:300px;top:200px;width:300px;height:200px;overflow:auto;display:none;">
<br>
<p>
测试一下<input type="text" vlaue="">
<br>
测试一下<input type="text" vlaue="">
<br>
</p>
</div>
</body>
</html>
鼠标点击事件中,DIV会隐藏,分集中情况,引用eventSource判断,事件源是DIV、文本框还是页面其他部分。
点击DIV时,DIV将点击的项放入文本框内。
点击文本框时,DIV显示情况不变。
点击页面其他部分,DIV隐藏。
Thank you!