希望实现的效果:
点击按钮后弹出弹窗(已实现),同时背景变暗,除了弹窗点击其他地方都不会有响应。
希望能得到一个简单的模板或者方法。
实践时遇到的问题:
采用显示隐藏的方法,不符合预期的想法,希望背景变暗但仍然能看到原页面而不是直接消失。
尝试用fixed放在顶层,但是显示不出来。
简单实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.modal-cover {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, .1);
z-index: 99;
display: none;
}
.modal {
width: 40%;
height: 300px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<button onclick="showModal()">show modal</button>
<div id="modal" class="modal-cover">
<div class="modal">
<button onclick="closeModal()">close modal</button>
</div>
</div>
<script>
var modal = document.getElementById('modal')
function showModal() {
modal.style.display = 'block'
}
function closeModal() {
modal.style.display = 'none'
}
</script>
</body>
</html>
可以写一个暗一点的透明遮罩层挡住,就点击不了了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
#mask {
position: fixed;
width: 100%;
height: 100%;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 99;
}
.hidden {
display: none;
}
#content {
position: fixed;
width: 80%;
height: 80%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #ffffff;
z-index: 99;
}
</style>
</head>
<body>
<div id="mask" class="hidden"></div>
<div id="content" class="hidden">
<div>这是content</div>
<button onclick="hiddenMask()">隐藏</button>
</div>
<button onclick="showMask()">显示</button>
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> -->
<script>
const mask = document.getElementById('mask')
const content = document.getElementById('content')
function showMask () {
mask.setAttribute('class', '')
content.setAttribute('class', '')
}
function hiddenMask () {
mask.setAttribute('class', 'hidden')
content.setAttribute('class', 'hidden')
}
</script>
</body>
</html>