js realizes pop up effect
- 2021-08-06 20:12:01
- OfStack
In this paper, we share the specific code of js to achieve pop-up effect for your reference. The specific contents are as follows
Thoughts:
1. Create a button and click the pop-up window
2. Establish a pop-up page with fixed positioning and default hiding
3. Place the pop-up contents in the middle of the pop-up page
4. js binds the event button and clicks it to display the pop-up page
5. The js event is bound to the span tag, and the pop-up page disappears after clicking
The code is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Pop-up window </title>
<link href="../css/ Pop-up window .css" type="text/css" rel="stylesheet">
</head>
<body>
<!-- Open pop-up button -->
<button id="btn"> Open the pop-up window </button>
<!-- Pop-up window -->
<div id="myModal">
<!-- Pop-up window head -->
<div class="modal">
<div class="modal-header">
<p> Hazard warning </p>
<span class="close">×</span>
</div>
<!-- Popup text -->
<div class="modal-content">
<p> You will enter 1 Insecure pages </p>
</div>
<!-- Bottom of pop-up window -->
<div class="modal-footer">
</div>
</div>
<script src="../js/ Pop-up window .js">
</script>
</body>
</html>
CSS:
#myModal{
display: none;
position: fixed;
z-index:1;
left:0;
top:0;
width: 100%;
height:100%;
overflow: auto;
background:rgba(0,0,0,0.5);
}
#myModal .modal{
width: 500px;
height:300px;
position: relative;
top:50%;
left:50%;
margin-top: -150px;
margin-left: -250px;
animation:animate 1s;
}
.modal .modal-header{
height:50px;
background:white;
color: #000;
line-height:50px;
border-bottom: 1px solid #000000;
}
.modal .modal-header p{
display: inline-block;
margin:0;
position: absolute;
left: 20px;
}
.modal .modal-header .close{
position: absolute;
right:20px;
font-size: 20px;
cursor:pointer;
}
.modal .modal-content{
background: white;
height:200px;
text-align: center;
line-height: 200px;
}
.modal .modal-content p{
margin:0;
}
.modal .modal-footer{
position: relative;
height:50px;
background: white;
}
/* Add Animation */
@keyframes animate{
from{top:0;opacity:0}
to{top:50%;opacity:1}
}
js:
window.onload=function () {
// Get pop-up button
var btn=document.getElementById("btn");
var close=document.getElementsByClassName("close")[0];
var myModal=document.getElementById("myModal");
// Button binding event
btn.onclick=function () {
// Get pop-up window
myModal.style.display="block";
}
close.onclick=function () {
myModal.style.display="none";
}
// The user clicks elsewhere to close the pop-up window
window.onclick=function (event) {
if(event.target ==myModal){
myModal.style.display="none";
}
}
}