我有一个代码问题,我不知道如何显示项目到02:30时,我的计时器号码到02:30,计时器也重置,当它到02:30,我希望项目显示,直到计时器滴答02:30。 有人能帮我解密码吗? 当定时器是02:30,定时器从03:00滴答到0并复位时,此div需要显示为无。
null
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function($) {
var threeMinutes = 60 * 3,
display = $('#timer');
startTimer(threeMinutes, display);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer" class="text-center" style="margin-top:100px;">03:00</h1>
<div class="alert alert-info">File List</div>
<div class="alert alert-info">File List</div>
null
你的意思是当计时器到达2:30时如何隐藏项目?
null
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
$(".alert").toggle(timer >= 150)
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function($) {
var threeMinutes = 60 * 3,
display = $('#timer');
startTimer(threeMinutes, display);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer" class="text-center" style="margin-top:100px;">03:00</h1>
<div class="alert alert-info">File List</div>
<div class="alert alert-info">File List</div>
这可能比您要求的要多,但这种逻辑最好分成几个部分,即几个函数和几个变量。 也就是说,通常限制引入项目全局范围的函数和变量的数量是一种好的做法,因此在这种情况下,尝试并封装这些函数和变量将是明智的做法。 有几种选择,其中一种可能是创建一个JavaScript类
,它将以有组织的方式封装所有逻辑,并且只在全局名称空间(类本身的名称空间)中引入单个名称。 例如:
class Timer {
constructor (opts) {
this.duration = opts.duration
this.ele = document.querySelector(opts.element)
this.hideAt = opts.hideAt
this.time = 0
this.timer = null
}
startTimer () {
clearInterval(this.timer)
this.time = this.duration
this.timer = setInterval(() => this.update(), 1000)
}
milliToMins (millis) {
const minutes = Math.floor(millis / 60000)
const seconds = ((millis % 60000) / 1000).toFixed(0)
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds
}
update () {
this.time -= 1000
this.ele.textContent = this.milliToMins(this.time)
if (this.time === this.hideAt) this.ele.style.display = 'none'
}
}
这样做还有一个额外的好处,那就是更加可定制,因为您可以轻松地更改显示计时器的元素,开始持续时间和隐藏该元素的时间,所有这些都只需更新“实例化”时传递给计时器的“选项”即可,例如:
const myTimer = new Timer({
element: '#timer',
duration: 3 * 60 * 1000,
hideAt: 2.5 * 60 * 1000
})
在实例化它之后,您可以通过调用:
myTimer.startTimer()
另外,值得注意的是,您实际上并不需要jQuery(这就是我用普通JavaScript编写jQuery的原因)。
下面是在JSFiddle中运行的示例:https://jsfiddle.net/gawpsoy8/