我有自举模式,我在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........-->
答案 0 :(得分:0)
此代码在您提供的codepen中为我工作!
$(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);
});
});
问题是你忘记将你的“秒”重新初始化为7(倒计时效果)!