html + css 实现一个弹窗
时间: 2023-11-24 18:08:10 浏览: 38
好的,以下是一个简单的弹窗的 HTML 和 CSS 实现:
HTML 代码:
```html
<button id="open-modal">打开弹窗</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个弹窗。</p>
</div>
</div>
```
CSS 代码:
```css
/* 隐藏弹窗 */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
/* 弹窗内容 */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* 关闭按钮 */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
```
JavaScript 代码:
```javascript
// 获取弹窗和打开按钮
var modal = document.querySelector(".modal");
var btn = document.querySelector("#open-modal");
var close = document.querySelector(".close");
// 点击按钮打开弹窗
btn.onclick = function() {
modal.style.display = "block";
}
// 点击关闭按钮或其他地方关闭弹窗
close.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
```
这个弹窗会在点击按钮时弹出,点击关闭按钮或其他地方会关闭。你可以根据自己的需求进行修改。