前端实践:如何实现一个弹窗
在前端开发中,我们经常会遇到需要设计弹窗的情形,今天就来看看如何用原生js写一个弹窗
功能说明
我们要实现的功能是点击按钮弹出弹窗,然后点击右上角的关闭按钮或者点击其他非弹窗的区域弹窗消失。
HTML
首先先写HTML布局:
<button id="button">点击打开弹窗</button>
<!-- 弹窗背景 -->
<div id="modal">
<!-- 弹窗 -->
<div id="modal-content">
这是一个弹窗
<span id="close">×</span>
</div>
</div>
效果:
CSS
<style>
* {
padding: 0px;
margin: 0px;
}
/* 弹窗背景 */
#modal {
width: 100%;
height: 100%;
/* 默认隐藏 */
/* display: none; */
/* 固定定位 */
position: fixed;
/* 设置在顶层 */
z-index: 1000;
/* 设置位置 */
left: 0;
top: 0;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
/* 弹窗内容 */
#modal-content {
position: relative;
background-color: #fff;
margin: 10% auto;
border: 1px solid #888;
width: 1000px;
height: 580px;
z-index: 1001;
}
/* 关闭按钮 */
#close {
position: absolute;
right: 20px;
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
/* 设置关闭按钮的鼠标指针 */
#close:hover,
#close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
效果:
然后我们要让弹窗先隐藏起来,使用display:none;或者visibility:hidden;
效果:
JavaScript
通过设置监听函数后来改变元素的样式display
<script>
// 点击按钮
var button = document.getElementById("button");
var modal = document.getElementById("modal")
button.onclick = function () {
modal.style.display = "block";
};
// 关闭按钮
document.getElementById("close").onclick = function () {
modal.style.display = "none";
};
// 点击其他领域(即弹窗背景)
window.onclick = function(event){
if(event.target ==modal){
modal.style.display = "none"
}
}
</script>
效果:
完善
最后我们根据需要,可以使弹窗的内容和图片无法被选中和复制
/* 设置页面不可选择,复制 */
-moz-user-select: none;
-o-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
设置图片无法被拖拽
<body ondragstart="window.event.returnValue=false;return false;" oncontextmenu="window.event.returnValue=false;return false;" onselectstart="event.returnValue=false;return false;">