DIV失去焦点隐藏问题解决办法【经验总结】
今天,QQ好友问我一个问题:他说他想要点击一个链接或按钮弹出一个div层,当鼠标在div范围以外的区域点击时,希望div隐藏不显示。刚开始,我对这个问题的第一反应就是:不就是个div的显示与隐藏嘛。看似很简单,但是我下班回家从6点写到8点半,整整花了2个多小时才彻底解决这个棘手的问题。主要是因为div它没有blur事件,所以问题变得很复杂了,只能通过监听document的单击事件了,然后适当的时候通过阻止事件冒泡即可解决问题,还有一个棘手的问题是,IE和FF对事件源对象的表示方式不一致,所以JS代码兼容性也必须考虑。
好了,问题的难点大致分析完了,要开始解决它。我首先说下的我解决思路。
刚开始我不想把问题复杂化了,我知道Jquery已经帮我们解决浏览器兼容性问题了,所以我首先考虑了应用Jquery类库来协助解决问题,
于是写了如下代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="jquery-1.5.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[type=button]").click(function(event){
$("#test").show();
event.stopPropagation();
});
$(document).click(function(){
$("#test").css("display","none");
})
$('#test').click(function(){
return false;
});
});
</script>
<style type="text/css">
#test{
width:100px;
height:26px;
font-size:12px;
text-align:center;
font-weight:600;
color:#0000CC;
left:50%;
position:absolute;
margin-left:-50px;
margin-top:80px;
border:1px #000000 solid;
padding:15px 5px 5px 5px;
height:auto;
display:none;
}
</style>
</head>
<body>
<input type="button" value="点我试试"/>
<div id="test">
白洋荷色
<table width="50" border="1">
<tr>
<td>123</td>
<td>345</td>
<td>567</td>
</tr>
<tr>
<td>222</td>
<td>444</td>
<td>666</td>
</tr>
<tr>
<td>111</td>
<td>999</td>
<td>666</td>
</tr>
</table>
</div>
</body>
</html>
IE6和FF下测试成功,OK!
但有时候你可能并不想引用JQuery类库,你想使用纯js方式实现,因为JQuery虽然帮你解决了问题,但是你还是不知道它到底帮你做了什么,而这也正是我在用Jquery方式解决后所想,我希望再把它还原成纯JS方式实现。于是我经过很多次的修改测试,最终写下了如下代码:
。。。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style type="text/css">
#test{
width:100px;
height:26px;
font-size:12px;
text-align:center;
font-weight:600;
color:#0000CC;
left:50%;
position:absolute;
margin-left:-50px;
margin-top:80px;
border:1px #000000 solid;
padding:15px 5px 5px 5px;
height:auto;
display:none;
}
</style>
</head>
<body>
<input type="button" value="点我试试" onClick="showDiv(event)"/>
<div id="test" onClick="cal(event)">
白洋荷色
<table width="50" border="1">
<tr>
<td>123</td>
<td>345</td>
<td>567</td>
</tr>
<tr>
<td>222</td>
<td>444</td>
<td>666</td>
</tr>
<tr>
<td>111</td>
<td>999</td>
<td>666</td>
</tr>
</table>
</div>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function showDiv(evt){
var d = $("test");
d.style.display = "block";
canclebubble(evt);
}
document.onclick = function(event){
var d = $("test");
d.style.display = "none";
}
function cal(evt){
canclebubble(evt);
return false;
}
//阻止事件冒泡
function canclebubble(evt){
var e=(evt)?evt:window.event;
if (window.event) {
e.cancelBubble = true;
} else {
e.stopPropagation();
}
}
</script>
</body>
</html>
IE6和FF下测试通过
本文来源 我爱IT技术网 http://www.52ij.com/jishu/97.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
