我正在研究一个简单的倒计时,该倒计时在我打开模态时运行,在我打开一次模数时有效。我的问题是当我再次关闭并打开它时,计数器同时显示不同的计数器。我尝试放入timer(0)
,但没有用,我也使用off()
,但计数器不再起作用。
希望你能帮助我,谢谢。
$('#myBtn').click(function(){
$('.modal').show();
timer(60);
});
$('.close').click(function(){
$('.modal').hide();
});
function timer(seconds){
var interval = setInterval(function() {
seconds--;
$('.note span').text(seconds);
if (seconds == 0) {
// Display a login box
clearInterval(interval);
}
}, 1000);
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<div class="note"><span>60</span></div>
</div>
</div>
答案 0 :(得分:2)
您应该清除模式关闭时的时间间隔,并将seconds
文本重设为60
。在interval
和timer
处理程序的范围内都有一个.close
变量,并在关闭时调用clearInterval
:
let interval;
$('#myBtn').click(function() {
$('.modal').show();
timer(60);
});
$('.close').click(function() {
clearInterval(interval);
$('.note span').text('60');
$('.modal').hide();
});
function timer(seconds) {
interval = setInterval(function() {
seconds--;
$('.note span').text(seconds);
if (seconds == 0) {
// Display a login box
clearInterval(interval);
}
}, 1000);
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<div class="note"><span>60</span></div>
</div>
</div>