在4399小游戏,网易云音乐mv,B站等浏览器页面上,我们经常能够看到遮罩层:
遮罩层设计可以用Vue框架实现,但其实Vue实现也是建立在原生实现的基础上,抽取其核心功能如下:
-
原页面(取消关灯):
-
关灯之后:
html架构
<body> <div id="main"> <div id="shadow"></div> <button id="btn">关灯</button> </div> </body>
这样基础结构就出来了:
请格外留意body内的结构:
-
main表示整个container,一般是整个屏幕
-
shadow作为遮罩层,一开始不显示,只有点击按钮才显示
-
button与shadow在同一dom级上(并列)
设计CSS
* { padding: 0; margin: 0; } html { height: 100%; width: 100%; } body { height: 100%; width: 100%; background-image: url("https://www.png8.com/imgs/2020/08/bb5f8741f8be53be.jpeg"); background-size: cover; } #main { height: 100%; width: 100%; } #shadow { position: absolute; visibility: hidden; background-color: #000; opacity: 0.8; top: 0; bottom: 0; left: 0; right: 0; } #btn { position: absolute; }
添加js逻辑
var btn = document.getElementById('btn'); var sha = document.getElementById('shadow'); btn.onclick = function() { sha.style.visibility = 'visible'; } sha.onclick = function() { sha.style.visibility = 'hidden'; }
完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { padding: 0; margin: 0; } html { height: 100%; width: 100%; } body { height: 100%; width: 100%; background-image: url("https://www.png8.com/imgs/2020/08/bb5f8741f8be53be.jpeg"); background-size: cover; } #main { height: 100%; width: 100%; } #shadow { position: absolute; visibility: hidden; background-color: #000; opacity: 0.8; top: 0; bottom: 0; left: 0; right: 0; } #btn { position: absolute; } </style> </head> <body> <div id="main"> <div id="shadow"></div> <button id="btn">关灯</button> </div> </body> <script> var btn = document.getElementById('btn'); var sha = document.getElementById('shadow'); btn.onclick = function() { sha.style.visibility = 'visible'; } sha.onclick = function() { sha.style.visibility = 'hidden'; } </script> </html>
本文地址:https://blog.csdn.net/weixin_44026604/article/details/107862296