html 点击遮罩关闭层,CSS实现带遮罩层可关闭的弹窗效果
时间: 2023-11-28 08:47:15 浏览: 221
HTML 部分:
```html
<div class="modal">
<div class="modal-content">
<h2>弹窗标题</h2>
<p>弹窗内容</p>
<button class="close">关闭</button>
</div>
<div class="modal-overlay"></div>
</div>
```
CSS 部分:
```css
.modal {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 9999;
display: none;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
.modal-overlay {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: -1;
}
.modal.show {
display: block;
}
.close {
display: block;
margin-top: 20px;
background-color: #ccc;
border: none;
padding: 5px 15px;
border-radius: 3px;
color: #000;
cursor: pointer;
}
.close:hover {
background-color: #aaa;
}
```
JavaScript 部分:
```javascript
const modal = document.querySelector('.modal');
const modalOverlay = document.querySelector('.modal-overlay');
const closeBtn = document.querySelector('.close');
modalOverlay.addEventListener('click', hideModal);
closeBtn.addEventListener('click', hideModal);
function hideModal() {
modal.classList.remove('show');
}
function showModal() {
modal.classList.add('show');
}
```
以上代码实现了一个带遮罩层可关闭的弹窗效果。当点击遮罩层或关闭按钮时,弹窗会自动关闭。
阅读全文