发现一个比较不错的方法,记录一下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title></title> <style type="text/css"> * { padding:0; margin:0; } #box { position:relative; margin:50px; } #pop { display:none; position:absolute; left:200px; top:100px; width:120px; height:120px; border:2px solid #ccc; background:#eee; } </style> <script type="text/javascript"> window.onload=function(){ var oBox=document.getElementById("box"); var obj=document.getElementById("pop"); var oBtn=document.getElementById("click"); oBtn.onclick=function(){ obj.style.display="block"; } document.onclick=function(event){ // var e=event || window.event;//兼容ie和非ie的event var aim=e.srcElement || e.target; //兼容ie和非ie的事件源 // if(e.srcElement){ var aim=e.srcElement; if(aim!=oBtn && aim!=obj){ obj.style.display="none"; } }else{ var aim=e.target; if(aim!=oBtn && aim!=obj){ obj.style.display="none"; } } } } </script> </head> <body> <div id="box"> <a href="javascript:;" id="click" >点击弹出</a> <div id="pop"> 弹出层内容呢 </div> </div> </body> </html>
来源参考:http://wenku.baidu.com/view/f86580737fd5360cba1adbc2.html