我根本不懂JavaScript。Bootstrap文档说到

通过JavaScript调用modal: $('#myModal').modal(options)

我不知道如何在页面加载上调用这个。使用Bootstrap页面上提供的代码,我可以成功地在元素单击上调用模态,但我希望它立即在页面加载上加载。


当前回答

在我的例子中,添加jQuery来显示模态不起作用:

$(document).ready(function() {
    $('#myModal').modal('show');
});

这似乎是因为模态有属性aria-hidden="true":

<div class="modal fade" aria-hidden="true" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

需要删除该属性以及上面的jQuery:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

请注意,我尝试将模态类从模态渐变更改为模态渐变,但这并不奏效。此外,将模态淡出类更改为模态显示类也阻止了模态关闭。

其他回答

就像其他人提到的,用display:block创建你的模态

<div class="modal in" tabindex="-1" role="dialog" style="display:block">
...

将背景放置在页面的任何地方,它不一定要在页面的底部

<div class="modal-backdrop fade show"></div> 

然后,为了能够再次关闭对话框,添加这个

<script>
    $("button[data-dismiss=modal]").click(function () {
        $(".modal.in").removeClass("in").addClass("fade").hide();
        $(".modal-backdrop").remove();
    });
</script>

希望这能有所帮助

我最近需要使用Django消息启动一个Bootstrap 5模态,不使用jQuery,也不使用按钮点击(例如,页面加载)。我是这样做的:

/ HTML模板

<div class="modal" id="notification">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Notification!</h5>
        <button type="button" class="btn-close"
                data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        {% for m in messages %}
          {{ m }}
        {% endfor %}
      </div>
      <div class="modal-footer justify-content-between">
        <a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
           type="button">
          Link/Button A
        </a>
        <button type="button" class="btn btn-primary"
                data-bs-dismiss="modal">
          Link/Button B
        </button>
      </div>
    </div>
  </div>
</div>

JS文件或模板

{% block javascript %}
  {{ block.super }}
  <script>
    var test_modal = new bootstrap.Modal(
      document.getElementById('notification')
    )
    test_modal.show()
  </script>
{% endblock javascript %}

这个方法在没有Django模板的情况下也可以工作;只需使用HTML并将JS放在一个文件或脚本元素中,在Bootstrap JS结束之前加载body元素。

你不需要javascript来显示模态

最简单的方法是将"hide"替换为"in"

class="modal fade hide"

so

class="modal fade in"

你需要添加onclick = "$('.modal').hide()"按钮关闭;

PS:我认为最好的方法是添加jQuery脚本:

$('.modal').modal('show');
<div id="ModalStart" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
          <p><i class="icon-spinner icon-spin icon-4x"></i></p>
    </div>
</div>

即使没有Javascript,你也可以在开始时显示它。只需删除类“hide”。

class="Modal"

你可能想要保持jquery.js延迟,以更快的页面加载。但是,如果jquery.js被延迟到$(window)。负载可能不工作。那么你可以试试

setTimeout(function(){$('#myModal').modal('show');},3000);

它会在页面完全加载后弹出你的模态(包括jquery)