我还搜索了在页面加载时自动打开模式的解决方案,并在以下解决方案中解决了它。如果你想让它自动打开,你可以在正常的引导语法中添加一个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});
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>