繁体   English   中英

如何触发页面加载模式

[英]how to trigger modal on page load

我有此HTML模态,由按钮单击触发

 <button type="button" class="btn btn-success mb-1" data-toggle="modal" data-target="#largeModal"> Large </button> <div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="largeModalLabel" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="largeModalLabel">Large Modal</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <p> There are three species of zebras: the plains zebra, the mountain zebra and the Grévy's zebra. The plains zebra and the mountain zebra belong to the subgenus Hippotigris, but Grévy's zebra is the sole species of subgenus Dolichohippus. The latter resembles an ass, to which it is closely related, while the former two are more horse-like. All three belong to the genus Equus, along with other living equids. </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Confirm</button> </div> </div> </div> </div> 

我想触发页面加载模式,而不是单击按钮。 我怎样才能做到这一点?

如果您使用的是Bootstrap (然后,我还假设您使用的是jQuery ),则它与正在加载的页面html中的以下代码一样简单。

 $('#largeModal').modal({show: true});

您也可以只模拟点击模式触发器:

$('.mb-1').trigger('click');

当然,请确保此代码位于模态标记之后 如果不可能,则必须将其包装在doc.ready中,例如

 $(function(){
    $('#largeModal').modal({show: true});
 })

要么

 $(function(){
    $('.mb-1').trigger('click');
 })

再次,这假设在您的代码中jQuery被分配为$

这是普通的JavaScript。 如果将onload="callBack()"放在body标记内,则可以编写一个函数来加载特定元素(在这种情况下为模态)。

有多种方法可以做到这一点。 最简单的是,您可以在script标签中选择所需的元素,并为其display: "inline"样式display: "inline" (或者您希望其显示)。 注意:您必须先通过设置display: none隐藏模态display: none

例:

身体:

<body onload="callBack()">
   -elements here-
</body>

脚本:

<script>
    var callBack = function() {
        document.querySelector("#largeModal").style.display = "inline";
    }
</script>

希望这可以帮助 :)

这些解决方案将起作用:

<body onload="script();">

要么

document.onload = function ...

甚至

window.onload = function ...

请注意, 最后一个选项是更好的选择,因为它不引人注目并且被认为是更标准的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM