如何在页面加载时显示Modal?QWeb模板实现方法问询
问题描述
我有一个带Modal窗口的页面,已经通过按钮和正确的data-bs-属性实现了Modal的显示与隐藏。现在希望页面加载时自动弹出这个Modal,常规方法是用JS获取元素调用.show(),但想知道能不能仅在QWeb模板内实现,有没有可行方案?
可行方案:两种模板内实现方式
方法1:直接修改Modal的CSS类(纯模板标记)
Bootstrap的Modal默认通过fade类隐藏,添加show和d-block类可以让它在页面加载时直接显示。同时需要手动添加模态框的背景层,否则点击页面其他区域无法关闭Modal:
<template id="my_template" name="Hello there"> <t t-call="portal.portal_layout"> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#my_modal"> Show Modal </button> <!-- 页面加载时自动显示的Modal --> <div id="my_modal" tabindex="-1" role="dialog" class="modal fade show d-block"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="my_modal_title">Hi</h5> <button type="button" class="btn text-danger" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true"><i class="fa fa-close"/></span> </button> </div> <div class="modal-body"> Content ... </div> </div> </div> </div> <!-- 手动添加模态框背景层 --> <div class="modal-backdrop fade show"></div> </t> </template>
注意:这种方式存在小缺陷——第一次关闭Modal后,再次用按钮打开时可能会有样式残留(比如show类不会被自动移除),因此更推荐下面的JS方法。
方法2:模板内嵌入内联JS(更可靠)
虽然你提到不想单独写JS,但在QWeb模板里直接嵌入内联脚本,也算“仅在模板中实现”,而且符合Bootstrap官方规范,不会有样式残留问题:
<template id="my_template" name="Hello there"> <t t-call="portal.portal_layout"> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#my_modal"> Show Modal </button> <div id="my_modal" tabindex="-1" role="dialog" class="modal fade"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="my_modal_title">Hi</h5> <button type="button" class="btn text-danger" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true"><i class="fa fa-close"/></span> </button> </div> <div class="modal-body"> Content ... </div> </div> </div> </div> <!-- 模板内嵌入内联JS,页面加载后自动显示Modal --> <script> document.addEventListener('DOMContentLoaded', function() { var myModal = new bootstrap.Modal(document.getElementById('my_modal')); myModal.show(); }); </script> </t> </template>
这种方式既保留了按钮控制的功能,又能在页面加载时自动弹出Modal,关闭后再次打开也不会有问题,是更稳妥的选择。
另外注意:你的按钮里data-bs-target属性少了#,正确写法是data-bs-target="#my_modal",上面的代码已经修正了这个问题。
内容的提问来源于stack exchange,提问作者Thomas Rossi
相关产品推荐
相关产品推荐

