我有 Bootstrap 模式,我在其中设置了它在 7 秒后自动关闭并且在此处运行良好。
我的问题是我在模态下也显示了计数器秒数,并且在第一次尝试时工作正常。 但是在第一次尝试之后,它不是从 0 秒开始,而是从任何随机数开始。我不知道我错过了什么。
$(function() {
$('.thank_you_modal').on('show.bs.modal', function() {
var myModal = $(this);
clearTimeout(myModal.data('hideInterval'));
myModal.data('hideInterval', setTimeout(function() {
myModal.modal('hide');
}, 7000));
var sec = 0;
function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function() {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
setTimeout(function() {
clearInterval(timer);
}, 7000);
});
});
#custom_modal .modal-content+span {
color: #fff;
text-align: center;
display: block;
font-size: 12px;
margin-top: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-toggle="modal" data-target="#custom_modal">Click me</a>
<!--.......... Modal ..........-->
<div class="modal fade thank_you_modal" id="custom_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<h2>Thank You</h2>
</div>
</div>
<span>This message will close in <span id="seconds">00</span> seconds</span>
</div>
</div>
<!--............Modal Ends........-->
最佳答案
此代码在您提供的代码笔中为我工作!
$(function(){
$('.thank_you_modal').on('show.bs.modal', function(){
var myModal = $(this);
clearTimeout(myModal.data('hideInterval'));
myModal.data('hideInterval', setTimeout(function(){
myModal.modal('hide');
}, 7000));
var sec = 7;
function pad(val) {
return val > 2 ? val : "0" + val;
}
var timer = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(--sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
setTimeout(function () {
clearInterval(timer);
sec = 7;
}, 7000);
});
});
问题是您忘记将“sec”重新初始化为 7(用于倒计时效果)!
关于javascript - 首次尝试 Bootstrap 模式后,计数器值无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44907750/