gpt4 book ai didi

javascript - 关闭模式后重置计时器

转载 作者:行者123 更新时间:2023-11-30 14:27:00 24 4
gpt4 key购买 nike

我正在开发一个简单的倒计时,当我打开一个模式时它会运行,当我打开它一次时它就会工作。我的问题是当我关闭并再次打开它时,计数器同时显示不同的计数器。我尝试放置 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">&times;</span>
<div class="note"><span>60</span></div>
</div>

</div>

最佳答案

您应该在模式关闭时清除间隔,并将 seconds 文本重置为 60。在 timer.close 处理程序的范围内都有一个 interval 变量,并在关闭时调用 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">&times;</span>
<div class="note"><span>60</span></div>
</div>

</div>

关于javascript - 关闭模式后重置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51758732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com