怎样在原html中加入弹窗,HTML中div弹窗的做法
时间: 2023-08-21 17:32:44 浏览: 51
要在原HTML中加入弹窗,可以使用HTML、CSS和JavaScript来实现。以下是使用div弹窗的做法:
1. 在HTML中添加一个div元素,用于弹窗的显示:
```html
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这里是弹窗内容</p>
</div>
</div>
```
2. 在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: #000;
text-decoration: none;
cursor: pointer;
}
```
3. 在JavaScript中添加事件监听器,以便在点击按钮时显示弹窗:
```javascript
// 获取按钮元素
var btn = document.getElementById("myBtn");
// 获取弹窗元素
var modal = document.getElementById("myModal");
// 获取关闭按钮元素
var span = document.getElementsByClassName("close")[0];
// 点击按钮时显示弹窗
btn.onclick = function() {
modal.style.display = "block";
}
// 点击关闭按钮或其他区域时隐藏弹窗
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
```
以上就是使用div弹窗的做法,您可以根据需要进行修改和扩展。