javascript - Bootstrap V5 手动调用模态 myModal.show() 不起作用(香草 javascript)
问题描述
在引导程序 5 中手动调用模态的正确方法是什么?
我想在页面打开时显示模式。我试过这个:
我的模态
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
...
...
...
</div>
</div>
</div>
我的脚本是
var myModal = document.getElementById('myModal');
document.onreadystatechange = function() {
myModal.show();
}
但在控制台日志中出现此错误:
myModal.show is not a function
at HTMLDocument.document.onreadystatechange
解决方案
模态插件通过数据属性或 JavaScript 按需切换隐藏内容。它还将 .modal-open 添加到 以覆盖默认滚动行为并生成 .modal-backdrop 以提供单击区域,以便在单击模态框外时关闭显示的模态框。[资源]
如何通过 Vanilla JavaScript 使用
用一行 JavaScript 创建一个模态框:
var myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
一个简单的例子:
var myModal = new bootstrap.Modal(document.getElementById("exampleModal"), {});
document.onreadystatechange = function () {
myModal.show();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"
integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I"
crossorigin="anonymous"
/>
<title>Hello, world!</title>
</head>
<body>
<div
class="modal fade"
id="exampleModal"
tabindex="-1"
role="dialog"
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>
<!-- JavaScript and dependencies -->
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"
integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/"
crossorigin="anonymous"
></script>
<script src="./app.js"></script>
</body>
</html>
至于您的代码,您没有按照正确的方式在 Vanilla JavaScript 中显示/切换模式。为什么你期望myModal.show()
在myModal
只是一个 DOM 元素时发生?
推荐阅读
- msbuild - 每次构建都具有持久唯一的 AssemblyName
- c# - LINQ 合并 2 个列表,保持序列和来源
- python - Django update_or_create 如果值相等则通过
- javascript - 使用 Gulp 连接和缩小后删除生成的 CSS 文件
- c++ - 如何停止在共享库中实现的阻塞 pthread_join()
- python - 匹配以逗号分隔的精确长度的所有单词
- python - 我如何正确处理多维 numpy 数组
- java - Java CriteriaBuilder:传递的类型 CriteriaBuilder.In 不适用于参数
- youtube - 在不阻止谷歌驱动器的情况下阻止 youtube
- c++ - 尝试在另一个 SDL2 上显示一个图像没有错误,但第二个图像不会显示