在JavaScript中实现自动弹出的div
模态窗口,通常涉及以下几个基础概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动弹出模态窗口示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- 模态窗口结构 -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<p>这是一个自动弹出的模态窗口!</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
/* 模态窗口背景 */
.modal {
display: none; /* 默认隐藏 */
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4); /* 半透明背景 */
}
/* 模态窗口内容 */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 居中显示 */
padding: 20px;
border: 1px solid #888;
width: 80%; /* 宽度 */
max-width: 500px;
border-radius: 5px;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}
/* 关闭按钮 */
.close-button {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close-button:hover,
.close-button:focus {
color: black;
text-decoration: none;
}
// 获取模态窗口元素
const modal = document.getElementById('myModal');
// 获取关闭按钮
const closeButton = document.querySelector('.close-button');
// 当页面加载完成后,自动显示模态窗口
window.onload = function() {
modal.style.display = 'block';
};
// 当用户点击关闭按钮时,隐藏模态窗口
closeButton.onclick = function() {
modal.style.display = 'none';
};
// 当用户点击模态窗口外部区域时,隐藏模态窗口
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
};
display
属性。通过以上步骤和示例代码,你可以实现一个自动弹出的div
模态窗口,并根据需要进行定制和优化。
领取专属 10元无门槛券
手把手带您无忧上云