<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.clearfix:after {
content: "";
display: block;
clear: both;
}
#btn {
display: block;
font-size: 1.5rem;
padding: 5px;
margin: 0 auto;
cursor: pointer;
}
.panel {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
width: 300px;
border: 1px solid;
border-radius: 5px;
background: #fff;
display: none;
z-index: 2;
}
.panel .close {
float: right;
margin-top: 15px;
margin-right: 15px;
font-size: 1.15rem;
cursor: pointer;
}
.panel .sure,
.panel .cancel {
border: 1px solid;
border-radius: 5px;
margin: 5px;
padding: 5px;
float: right;
cursor: pointer;
}
.shadow {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #ccc;
opacity: 0.75;
z-index: 1;
display: none;
}
</style>
</head>
<body>
<button id="btn">点我跳出模态框</button>
<div class="panel clearfix">
<div class="close">X</div>
<h1>我是一级标题</h1>
<p>我是一大段文字</p>
<div class="cancel">取消</div>
<div class="sure">确定</div>
</div>
<div class="shadow"></div>
<script>
function $(str) {
return document.querySelector(str);
}
var panel = $(".panel");
var btn = $("#btn");
var close = $(".panel>.close")
var shadow = $(".shadow")
btn.addEventListener("click", function(e) {
e.stopPropagation();
panel.style.display = "block";
shadow.style.display = "block";
})
close.addEventListener("click", function() {
panel.style.display = "none";
shadow.style.display = "none";
})
panel.addEventListener("click", function(e) {
e.stopPropagation();
})
window.addEventListener("click", function() {
panel.style.display = "none";
shadow.style.display = "none";
})
</script>
</body>
</html>
原生JS实现弹出、关闭模态框
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 在网页中我们经常会用到模态框,一般会用于显示表单或者是提示信息。由于模态框涉及到页面上比较多的交互效果,最简单的交...
- 在pc端开发,模态框是一个很常用的插件,之前一直用的第三方插件,比如bootstrap,jQuery的模态框插件,...
- 使用纯 CSS 实现 500px 照片列表布局 文章很长,因为介绍了如何一步一步进化到最后接近完美的效果的,不想读...