我希望你们可以帮助我,因为我对javascripts知之甚少。 我一直在使用相同的计时器,它总是像魅力一样。虽然当我试图在我的页面上再次添加相同的计时器时,只有1个可以工作。
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.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10.1,
display = document.querySelector('.time');
startTimer(fiveMinutes, display);
};
<span class="time">10:07</span>
<br/>
<br/>
<br/>
<span class="time">10:07</span>
我已经尝试为另一个类添加第二个脚本,但遗憾的是没有工作结果......
有人能帮帮我吗?因为我对javascript知之甚少,所以JSfiddle首选!提前谢谢!
答案 0 :(得分:0)
使用querySelectorAll
function startTimer(duration, displays) {
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;
Array.prototype.forEach.call(displays, function(display) {
display.textContent = minutes + ":" + seconds;
});
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10.1,
displays = document.querySelectorAll('.time');
startTimer(fiveMinutes, displays);
};
<span class="time">10:07</span>
<br/>
<br/>
<br/>
<span class="time">10:07</span>
答案 1 :(得分:0)
function startTimer(duration, display, display2) {
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.textContent = minutes + ":" + seconds;
display2.textContent = display.textContent;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10.1,
display = document.querySelector('.time');
display2 = document.querySelector('.time2');
startTimer(fiveMinutes, display ,display2);
};