html+js实现自定义弹窗
以下是一个简单的HTML和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>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
</style>
</head>
<body>
<button id="openBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span id="closeBtn">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("openBtn");
// Get the <span> element that closes the modal
var span = document.getElementById("closeBtn");
// When the user clicks on 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";
}
}
</script>
</body>
</html>
这段代码实现了一个基本的自定义弹窗,当用户点击“Open Modal”按钮时弹窗会显示,点击弹窗内的“x”按钮或者点击弹窗外的任何地方都可以关闭弹窗。
评论已关闭