gpt4 book ai didi

javascript - 制作一个javascript倒数计时器

转载 作者:行者123 更新时间:2023-11-30 06:16:19 26 4
gpt4 key购买 nike

我正在制作一个倒数计时器,其中天时分秒的文本就在其各自值的下方。它也必须响应。我在下面有一些代码:

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 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 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);

// Display the result in the element with id="demo"


document.getElementById("timer").innerHTML = "<h1>" + days + " <span> days </span>: " + hours + " <span>hours</span>: " + minutes + " <span>minutes </span>: <font color='red'>" + seconds + "<span> s</span></font> </h1>";

// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);

document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);
<div align="center" id="timer"></div>

如果日期符号 D 在日期值的左侧,但我希望它在右侧,我的代码就会出现问题。我的意思是就像下面的图片一样j

最佳答案

您可以将文本包装在<div> 中创建换行符。其次创建一个接受 text 的函数, valuecolor作为参数并返回 html 字符串。

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();

function timePart(val,text,color="black"){
return `<h1 class="timer" style="color:${color};">${val}<div>${text}</div></h1>`
}

// 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 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);

// Display the result in the element with id="demo"

let res = timePart(days,'days') + timePart(hours,'hours') + timePart(minutes,'Mins') + timePart(seconds,'Seconds','red');
document.getElementById("timer").innerHTML = res

// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);

document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);
.timer{
display:inline-block;
padding:10px;
}
<div align="center" id="timer"></div>

关于javascript - 制作一个javascript倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937350/

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