推荐答案
// www.javascriptcn.com code example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Modal</title>
<style>
/* 模态框背景 */
.modal-background {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
}
/* 模态框内容 */
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
width: 300px;
text-align: center;
}
/* 关闭按钮 */
.close-button {
float: right;
cursor: pointer;
}
</style>
</head>
<body>
<button id="openModal">Open Modal</button>
<div id="modal" class="modal-background">
<div class="modal-content">
<span class="close-button" id="closeModal">×</span>
<p>This is a simple modal!</p>
</div>
</div>
<script>
// 获取元素
const modal = document.getElementById('modal');
const openModalButton = document.getElementById('openModal');
const closeModalButton = document.getElementById('closeModal');
// 打开模态框
openModalButton.addEventListener('click', () => {
modal.style.display = 'flex';
});
// 关闭模态框
closeModalButton.addEventListener('click', () => {
modal.style.display = 'none';
});
// 点击模态框外部关闭
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
</script>
</body>
</html>本题详细解读
1. HTML 结构
- 按钮:
<button id="openModal">Open Modal</button>用于触发模态框的显示。 - 模态框背景:
<div id="modal" class="modal-background">是模态框的背景层,覆盖整个页面。 - 模态框内容:
<div class="modal-content">是模态框的主要内容区域,包含关闭按钮和文本内容。
2. CSS 样式
- 模态框背景:
.modal-background使用position: fixed固定在页面上,覆盖整个视口。背景颜色为半透明的黑色 (rgba(0, 0, 0, 0.5)),并使用flex布局将内容居中。 - 模态框内容:
.modal-content是模态框的主要内容区域,设置了背景颜色、内边距、圆角、宽度和文本居中。 - 关闭按钮:
.close-button是一个简单的关闭按钮,使用float: right将其放置在右上角,并设置了cursor: pointer以显示手型光标。
3. JavaScript 逻辑
- 打开模态框:通过
openModalButton.addEventListener('click', () => { ... })监听按钮点击事件,点击后将模态框的display属性设置为flex,使其显示。 - 关闭模态框:通过
closeModalButton.addEventListener('click', () => { ... })监听关闭按钮点击事件,点击后将模态框的display属性设置为none,使其隐藏。 - 点击模态框外部关闭:通过
window.addEventListener('click', (event) => { ... })监听窗口点击事件,如果点击的是模态框背景 (event.target === modal),则关闭模态框。
4. 总结
这个简单的模态框实现展示了如何使用 HTML、CSS 和 JavaScript 创建一个基本的模态框。通过监听按钮点击事件和窗口点击事件,实现了模态框的显示和隐藏功能。