【问题标题】:Close Bootstrap modal on the delay using jQuery使用 jQuery 在延迟上关闭 Bootstrap 模态
【发布时间】:2018-12-13 11:20:08
【问题描述】:

我尝试:

  • 显示模态
  • 等待 3 秒
  • 隐藏模态

为什么它不起作用?

我的代码:

var $modal = $("#exampleModal");

$modal
  .modal("show")
  .delay(3000)
  .modal("hide")
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <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>

我知道an answer to the "bootstrap modal close after 4 seconds or user click" 的问题,但我希望纯 jQuery 解决方案让我的代码更加一致。


UDPATE:我特别想使用jQuery .delay() 方法。

【问题讨论】:

  • 您不了解 jQuery .delay 的工作原理。它仅适用于 jQuery 效果队列,因此非常适合幻灯片和淡入淡出等,但不会延迟 setTimeout 之类的延迟。它不能替代 JavaScript 的原生 setTimeout 函数。

标签: javascript jquery html bootstrap-4 bootstrap-modal


【解决方案1】:

您可以使用 javascript 函数 setTimeout() 以您想要的预定义延迟执行隐藏。

注意:我不确定您是否了解 jQuery .delay 的工作原理。它仅适用于 jQuery 效果队列,因此非常适合幻灯片和淡入淡出等,但不会延迟 setTimeout 之类的延迟。

它不能替代 JavaScript 的原生 setTimeout 函数。

var $modalDialog = $("#exampleModal");
$modalDialog.modal('show');

setTimeout(function() {
  $modalDialog.modal('hide');
}, 3000);

如果你真的想要 delay 的东西,你可以看看使用 Underscore 的 _.delay() 函数:

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.

很像setTimeout,在等待毫秒后调用函数。如果您传递可选参数,它们将在调用时转发给函数。

http://underscorejs.org/#delay

【讨论】:

  • 没有jquery怎么办,有没有类似data-dismis-delay属性的东西?
猜你喜欢
  • 1970-01-01
  • 2014-02-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 2017-01-16
  • 2019-10-07
  • 2021-11-10
相关资源
最近更新 更多