当然,下面是一个简单的JavaScript弹窗效果的源码示例。这个示例包括HTML、CSS和JavaScript部分,用于创建一个自定义的弹窗。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Modal</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="openModalBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close-btn">×</span>
<p>This is a custom modal!</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* Close Button */
.close-btn {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close-btn:hover,
.close-btn:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("openModalBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close-btn")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
这种弹窗效果可以用于各种网页应用中,例如:
希望这个示例对你有帮助!如果有任何问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云