这就是我所拥有的。
有些人建议我应该使用 class
而不是 id
,这是正确的。
另一方面,如果我使用一个类,我不知道 getelementsbyclassname
是否有效,因为当我尝试它时。当我运行 html 页面时,甚至没有一个时钟弹出。
// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
p {
text-align: center;
font-size: 60px;
}
<p Id="demo"></p>
<p Id="demo"></p>
<p Id="demo"></p>
最佳答案
当按类处理元素时,您可能需要使用:
您需要循环返回的 NodeList收集并分配值。
在ES6中你可以使用
[...myNodeList].forEach( node => {
/* do something to node */
});
在古老的 JS 中,它看起来像:
for ( var i = 0; i < myNodeList.length; i++ ) {
/* do something to myNodeList[i] */
}
// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var dif = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var d = Math.floor(dif / (1000 * 60 * 60 * 24));
var h = Math.floor((dif % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var m = Math.floor((dif % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((dif % (1000 * 60)) / 1000);
var formatted = d + "d " + h + "h " + m + "m " + s + "s ";
// Output the result in an element with class="demo"
[...document.querySelectorAll(".demo")].forEach(el => el.innerHTML = dif < 0 ? "EXPIRED" : formatted );
// If the count down is over, stop the interval
if (dif < 0) {
clearInterval(x);
}
}, 1000);
<p class="demo"></p>
<p class="demo"></p>
<p class="demo"></p>
关于javascript - 如何制作多个倒计时时钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47961267/