Bootstrap4 模态框学习笔记

什么是模态框?

模态框(Modal)就是浮现在页面上层的一块区域,它需要用户去交互才能关闭。在这个弹窗中,我们通常可以展示一些新闻、广告、信息等等。模态框对于一个网页应用来说有非常多的作用。比如登录框、注册框、评论框等。

如何使用 Bootstrap4 模态框?

Bootstrap4 为我们提供了一个非常强大且易用的模态框组件,只需要通过简单的 HTML 和 JavaScript 就可以快速创建一个模态框。

步骤1:包含必要的文件

首先,我们需要在项目页面中引入必要的 CSS 和 JS 文件。

htmlCopy Code
<!-- 引入 Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css"> <!-- 引入 jQuery --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- 引入 Bootstrap JavaScript --> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>

步骤2:创建模态框结构

接着,我们需要创建一个模态框的结构。一般情况下,模态框分为三个部分:

  • 头部(header):用于展示模态框的标题和关闭按钮。
  • 主体(body):用于展示模态框的内容。
  • 底部(footer):用于展示模态框的操作按钮。
htmlCopy Code
<div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- 头部 --> <div class="modal-header"> <h4 class="modal-title">Modal Header</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- 主体 --> <div class="modal-body"> <p>Some text in the modal.</p> </div> <!-- 底部 --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div>

步骤3:触发模态框

最后,我们需要创建一个按钮或者链接来触发模态框的显示。

htmlCopy Code
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Open Modal</button>

这个按钮将会触发一个 ID 为“myModal”的模态框。

模态框实例

下面是一个完整的基于 Bootstrap4 的模态框实例:

htmlCopy Code
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Bootstrap Modal Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Bootstrap Modal Example</h2> <!-- Button to Open the Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Open modal </button> <!-- The Modal --> <div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Modal Heading</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> Modal body text goes here. </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> </body> </html>

当我们点击“Open modal”按钮时,就会出现一个 ID 为“myModal”的模态框。