弹窗的简单实现
Posted JackySei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了弹窗的简单实现相关的知识,希望对你有一定的参考价值。
js原生实现效果如图
<!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">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<!-- 打开弹窗按钮 -->
<button id="myBtn">打开弹窗</button>
<!-- 弹窗 -->
<div id="myModal" class="modal">
<!-- 弹窗内容 -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>头部</h2>
</div>
<div class="modal-body">
<p>弹窗文本...</p>
<p>弹窗文本...</p>
</div>
<div class="modal-footer">
<h3>底部</h3>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
/* 弹窗 (background) */
.modal {
display: none; /* 隐藏 */
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
/* 弹窗内容 */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* 添加动画 */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* 关闭按钮 */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header,.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
.modal-body {padding: 2px 16px;}
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.querySelector('.close');
// 点击按钮打开弹窗
btn.onclick = function() {
modal.style.display = "block";
}
// 关闭弹窗
span.onclick = function() {
modal.style.display = "none";
}
// 在用户点击其他地方时,关闭弹窗
window.onclick = function(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
以上是关于弹窗的简单实现的主要内容,如果未能解决你的问题,请参考以下文章