gpt4 book ai didi

javascript - 同一页面多个倒计时

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

我需要一些有关 javascript 代码的帮助,我尝试获取适用于同一页面上的多个倒计时器的代码。我尝试了下面的代码但没有成功。

    <div class="expirydiv">Jan 02,2019</div>
<div class="expirydiv">jun 15,2019</div>

<script>
// Set the date we're counting down to

var ps = document.querySelectorAll("div.expirydiv");

var countDownDate = new Date(ps).getTime();

// Update the count down every 1 second

var x = setInterval(function() {

// Get today's date and time

var now = new Date().getTime();

// Find the distance between now and 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 classname="expirydiv"

for(var i=0; i<ps.length; i++){
ps[i].innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";

// If the count down is over, write some text

if (distance < 0) {
clearInterval(x);
ps[i].innerHTML = "EXPIRED";
}
}
}, 1000);

</script>

上面代码的结果如下所示:

    NaNd NaNh NaNm NaNs
NaNd NaNh NaNm NaNs

这段代码有什么问题,我认为查询选择器无法选择 div.expirydiv 作为日期。

最佳答案

您正在使用多个倒计时,因此您需要迭代它们并设置计时器。

var ps = document.querySelectorAll("div.expirydiv");
ps.forEach(function(timer){
var countDownDate = new Date(timer.innerText).getTime();

var x = setInterval(function() {

var now = new Date().getTime();
var distance = countDownDate - now;
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);

timer.innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
timer.innerHTML = "EXPIRED";
}

}, 1000);
});
<div class="expirydiv">Dec 02,2019</div>
<div class="expirydiv">Dec 15,2019</div>

关于javascript - 同一页面多个倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779896/

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