Bootstrap V5 手动调用模态 myModal.show() 不起作用(vanilla javascript)

mja*_*ade 9 javascript bootstrap-5

在 bootstrap 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>
Run Code Online (Sandbox Code Playgroud)

我的脚本是

var myModal = document.getElementById('myModal');
document.onreadystatechange = function() {
   
    myModal.show();
}
Run Code Online (Sandbox Code Playgroud)

但在控制台日志中出现此错误:

 myModal.show is not a function
    at HTMLDocument.document.onreadystatechange
Run Code Online (Sandbox Code Playgroud)

Ron*_*ici 22

如果您通过以下方式使用 Bootstrap 5+,请执行以下操作<script src="..." ></script>

let modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('myModal')) // Returns a Bootstrap modal instance
// Show or hide:
modal.show();
modal.hide();
Run Code Online (Sandbox Code Playgroud)

在此处查看更多信息:https ://getbootstrap.com/docs/5.0/components/modal/#getorcreateinstance

将 BS 带到您的页面,如下所示:https ://getbootstrap.com/docs/5.3/getting-started/introduction/

  • 到底为什么这个文档从 v5.2 版本的 [Modal 页面](https://getbootstrap.com/docs/5.2/components/modal) 中删除了? (2认同)

Yer*_*ran 13

  1. 新建一个modal实例,然后调用show方法(见使用要点)
var myModal = new bootstrap.Modal(document.getElementById('exampleModal'))
myModal.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

参考:https : //v5.getbootstrap.com/docs/5.0/components/modal/#options

注意:Bootstrap v5 不再使用 jquery,而是使用 javascript。bootstrap v5 有很多变化,如果你在一家公司工作并且愿意使用 Bootstrap v5,那么请检查所有的变化。


Mat*_*een 13

模态插件通过数据属性或 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();
};
Run Code Online (Sandbox Code Playgroud)
<!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">&times;</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>
Run Code Online (Sandbox Code Playgroud)

至于您的代码,您没有按照正确的方式在 Vanilla JavaScript 中显示/切换模式。为什么你期望myModal.show()发生 whilemyModal只是一个 DOM 元素?


小智 13

根据 OP 提供的 javascript 代码,我认为这里的实际目标是通过 DOM 元素访问组件。我也寻找了一种方法来做到这一点,所以想分享我已经找到(或没有找到)的内容。

v4-它是可能的并且通常与早期版本一起使用。在 v4 中,我们可以轻松地通过 jQuery 使用它,尽管该组件是由数据属性初始化的,而不是直接从 js 初始化的。

$('#myModal').modal('show');
Run Code Online (Sandbox Code Playgroud)

v5.0.0-beta2在新版本中,文档中为另一种类型的组件提供了一个非常有前景的 api 示例。然而,目前它似乎不起作用。(https://getbootstrap.com/docs/5.0/getting-started/javascript/#asynchronous-functions-and-transitions

var myModal = document.getElementById('myModal')
var modal = bootstrap.Modal.getInstance(myModal) 
console.log(modal) // null
Run Code Online (Sandbox Code Playgroud)

由于所有组件都使用相同的基本组件,人们可能会认为可以通过使用 getInstance api 方法来获取模态以及其他组件(如下拉、折叠、轮播等)的实例,但这是不可能的。至少对于当前的测试版来说是这样。

最后一点:仍然可以在 v5 脚本之前包含 jQuery 并实现此目的。(https://codepen.io/cadday/pen/Jjbvxvm

window.onload = function() {
  console.log(jQuery('#myModal').modal('show'));
}
Run Code Online (Sandbox Code Playgroud)

  • 为了使 bootstrap.Modal.getInstance 工作,您需要创建该实例。为此,您必须最好在创建模式时执行“new bootstrap.Modal(myModal)”。 (2认同)

oVi*_*oVi 5

我还寻找了一种在页面加载时自动打开模式的解决方案,并在以下解决方案中解决了该问题。如果您想让它自动打开,您可以将data-auto-open属性添加到正常的引导语法中。如果未设置该属性,模态是否也以标准方式工作。

如果您想在页面加载后立即打开淡入淡出效果,我还添加了一个选项来暂时删除淡入淡出效果。要实现这一点,只需使用data-auto-open="instant"而不是空的data-auto-open属性。关闭一次后,您想手动重新打开它,它会再次出现淡入淡出效果吗?

Bootstrap 5.0.0-Beta3的 TypeScript 中的工作解决方案如下所示:

// @ts-ignore
import { Modal } from 'bootstrap';

window.addEventListener('DOMContentLoaded', (event) => {
    const selector = '[data-auto-open]';
    const modalElement: HTMLElement | null = document.querySelector(selector);

    if (!modalElement) {
        return;
    }

    const mode = modalElement.dataset.autoOpen;
    const fade = modalElement.classList.contains('fade');

    if (fade && mode === 'instant') {
        modalElement.classList.remove('fade');
    }

    const modal = new Modal(modalElement, {});

    if (fade && mode === 'instant') {
        // There's currently a bug in the backdrop when the fade class 
        // will be added directly after the modal was opened to have the
        // close animation
        // modalElement.addEventListener('shown.bs.modal', function (event) {
        modalElement.addEventListener('hidden.bs.modal', function (event) {
            modalElement.classList.add('fade');
        }, {once : true});
    }

    modal.show();
}, {once : true});
Run Code Online (Sandbox Code Playgroud)

HTML 是标准的:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
    Demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" data-auto-open>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">
                    Example Modal title
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
                eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-cancel" data-bs-dismiss="modal">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)