10
社区成员




要在网页上实现点击<a>
标签后弹出一个响应式的可关闭弹窗,我们可以使用HTML、CSS和JavaScript(或jQuery)来完成。下面是一个简单的示例,展示了如何实现这个功能。
1<!DOCTYPE html>
2<html lang="zh">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>响应式弹窗示例</title>
7 <link rel="stylesheet" href="styles.css">
8</head>
9<body>
10 <!-- 弹窗触发链接 -->
11 <a href="#" id="openModal">点击我打开弹窗</a>
12
13 <!-- 弹窗结构 -->
14 <div class="modal" id="myModal">
15 <div class="modal-content">
16 <span class="close">×</span>
17 <p>这是一串展示的文字。这是一个响应式的弹窗,你可以在这里看到一些信息。</p>
18 </div>
19 </div>
20
21 <!-- 引入jQuery库 -->
22 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
23 <!-- 自定义JavaScript文件 -->
24 <script src="scripts.js"></script>
25</body>
26</html>
1.modal {
2 display: none;
3 position: fixed;
4 z-index: 1;
5 left: 0;
6 top: 0;
7 width: 100%;
8 height: 100%;
9 overflow: auto;
10 background-color: rgba(0,0,0,0.4);
11}
12
13.modal-content {
14 background-color: #fefefe;
15 margin: 15% auto;
16 padding: 20px;
17 border: 1px solid #888;
18 width: 80%;
19 max-width: 600px;
20}
21
22.close {
23 color: #aaa;
24 float: right;
25 font-size: 28px;
26 font-weight: bold;
27}
28
29.close:hover,
30.close:focus {
31 color: black;
32 text-decoration: none;
33 cursor: pointer;
34}
1$(document).ready(function() {
2 // 当点击链接时,显示模态框
3 $("#openModal").click(function(event) {
4 event.preventDefault();
5 $("#myModal").css("display", "block");
6 });
7
8 // 当点击模态框外部或关闭按钮时,隐藏模态框
9 $(".close, .modal").click(function() {
10 $("#myModal").css("display", "none");
11 });
12
13 // 当点击模态框内部时,阻止关闭
14 $(".modal-content").click(function(event) {
15 event.stopPropagation();
16 });
17});
这段代码实现了以下功能:
id="openModal"
的<a>
标签时,会阻止默认的链接行为,并显示带有id="myModal"
的模态框。