b-k*_*kat 7 javascript twitter-bootstrap bootstrap-modal
我很难在一段时间后自动关闭Bootstrap模态.
这是我用来在4秒内关闭模态的js代码:
setTimeout(function() { $('#myModal').modal('hide'); }, 4000);
两个基本问题:
(A)当加载html页面(包含模态)时,模态Timeout似乎在模态甚至显示之前运行.单击页面中的链接后,将设置模式.如果在页面加载时没有立即单击链接,则模式将仅短暂出现然后立即关闭,因为基本上超时时间是在加载html页面时开始的,而不是在显示模式时.
(B)如果用户点击链接以第二次(或第3次,第4次等)启动模态,则模态显示正确,但在该时间段后不会关闭.它只是保持打开状态,直到用户手动关闭它.
所以......这两个问题是:
(1)在运行时钟之前,如何让模态超时周期等到显示模态.
(2)如何使模式在第二次和第三次显示时仍有正常的Timeout功能?
(下面这个链接提出的答案看起来很有希望,但对我不起作用.也许它们不适用于Bootstrap 3?如何在一分钟后自动关闭bootstrap模式对话框)
下面的代码看起来非常有前景,但即使将'shown'更改为'shown.bs.modal'后也无效.或者我可能将此代码放在错误的位置?
var myModal = $('#myModal').on('shown', function () {
clearTimeout(myModal.data('hideInteval'))
var id = setTimeout(function(){
myModal.modal('hide');
});
myModal.data('hideInteval', id);
})
Run Code Online (Sandbox Code Playgroud)
非常感谢任何建议!
Agu*_*ico 14
我不太确定你的HTML,所以我做了一个完整的例子:
HTML:
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Open Modal</a>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h4>Header</h4>
</div>
<div class="modal-body">
Modal Content
</div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
$(function(){
$('#myModal').on('show.bs.modal', function(){
var myModal = $(this);
clearTimeout(myModal.data('hideInterval'));
myModal.data('hideInterval', setTimeout(function(){
myModal.modal('hide');
}, 3000));
});
});
Run Code Online (Sandbox Code Playgroud)
与您的代码的主要区别:
Mat*_*vid 11
我想这取决于你如何显示你的模态.但是你可以在事件监听器中设置超时?
这是一个JSFiddle来演示如何实现它.基本上,您在事件发生时将执行的函数中添加超时.
// Select the element you want to click and add a click event
$("#your-link").click(function(){
// This function will be executed when you click the element
// show the element you want to show
$("#the-modal").show();
// Set a timeout to hide the element again
setTimeout(function(){
$("#the-modal").hide();
}, 3000);
});
Run Code Online (Sandbox Code Playgroud)
如果您侦听的事件是单击链接,则可能必须通过使用来阻止默认操作event.preventDefault().你可以在这里找到更多信息
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
54232 次 |
| 最近记录: |