Bootstrap Modal无法正常显示,求解决(附复现示例代码)
Bootstrap 4.6 Modal无法显示的解决方法
你的代码问题在于缺少Bootstrap 4组件必需的JavaScript依赖文件。Bootstrap 4的模态框(Modal)功能依赖jQuery和Popper.js才能实现交互逻辑,你只引入了Bootstrap的CSS,没有加载这两个核心JS文件,导致点击按钮无法触发模态框显示。
解决步骤
在HTML的</body>闭合标签之前,按顺序引入以下三个JS文件(顺序不能颠倒,Bootstrap JS依赖前两者提供的功能):
- jQuery
- Popper.js
- Bootstrap 4.6的JS文件
修正后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie=edge"/> <title>SOMETHING</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous" /> </head> <body> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> ... </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> <!-- 新增的JS依赖 --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js" integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+" crossorigin="anonymous"></script> </body> </html>
补充说明
- jQuery:Bootstrap 4的所有JavaScript组件都基于jQuery构建,没有它无法触发任何交互事件。
- Popper.js:用于处理模态框、下拉菜单等组件的定位逻辑,确保它们在页面中正确显示。
内容的提问来源于stack exchange,提问作者libik
相关产品推荐
相关产品推荐

