遮罩层实现方式二
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #login-register span{ display: inline-block; padding: 6px 10px; background: #E3E3E3; cursor: pointer; } #mask{ height: 2000px; width: 100%; background: #666; position: fixed; top: 0; left: 0; opacity: 0.6; z-index: 100; } #loginPage{ width: 430px; height: 295px; background: url(img/TencentLogin.png) no-repeat; position: fixed; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); z-index: 1000; } #close{ float: right; height: 30px; width: 30px; margin: 10px 10px 0 0; background: url(img/close.png) no-repeat; cursor: pointer; } </style> </head> <body> <div id="login-register"> <span id="login">登录</span> <span id="register">注册</span> </div> <!--遮罩层--> <!--<div id="mask"> </div>--> <!--登录页面--> <!--<div id="loginPage"> <span id="close"></span> </div>--> </body> <script type="text/javascript"> var login = getId("login"); var register = getId(register); //登录按钮的点击事件 login.addEventListener('click',showLogin); function showLogin(){ //创建遮罩层 var mask = document.createElement('div'); //给遮罩层设置id mask.id = "mask"; //设置遮罩层的大小 var mh = screen.height + "px"; var mw = screen.width + "px";//需要自己加单位,通过screen.width或screen.availWidth获取到的只是数值,并不带单位 // alert(mh) mask.style.height = mh; mask.style.width = mw; //将遮罩层添加到页面中 document.body.appendChild(mask); //创建登陆框 var loginPage = document.createElement('div'); loginPage.id = "loginPage"; //创建X var close = document.createElement('span'); close.id = "close"; //将X添加到loginPage登陆框中 loginPage.appendChild(close); document.body.appendChild(loginPage); //X的事件 close.addEventListener('click',closeLogin); //点击遮罩层关闭登陆框 mask.addEventListener('click',closeLogin); function closeLogin(){ loginPage.style.display = "none"; mask.style.display = "none"; } } //通过函数封装通过id获取元素 function getId(id){ return document.getElementById(id); } </script> </html>