<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>点击空白处隐藏盒子</title> <style> #mask{ width: 100%; height:2000px; font-weight:bold;">#000; opacity: 0.4; filter:alpha(opacity = 40); position: fixed; top:0; left: 0; display: none; } body{ height: 2000px; } #box{ width: 300px; height: 300px; font-weight:bold;">#fff; position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -150px; display: none; } </style></head><body> <a href="javascript:;" id="login">注册</a> <a href="javascript:;">登录</a> <div id="mask"></div> <div id="box"></div></body><script>// var function $(id){return document.getElementById(id)};var login = document.getElementById("login");var mask = document.getElementById("mask");var box = document.getElementById("box") //阻止冒泡 login.onclick = function(event){ var event = event||window.event; if(event && event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble = true; } mask.style.display = "block"; box.style.display = "block"; document.body.style.overflow = "hidden"; } document.onclick = function(event){ var event = event || window.event; //判断当前对象是否是自己 var targetId = event.target ? event.target.id : event.srcElement.id; //兼容写法 if(targetId != "box"){ mask.style.display = "none"; box.style.display = "none"; document.body.style.overflow = "visible"; }else{ mask.style.display = "block"; box.style.display = "block"; document.body.style.overflow = "hidden"; } } </script></html>
时间: 2024-11-04 14:46:32