gpt4 book ai didi

单击开始按钮时的 JavaScript 倒计时器,显示小时、分钟和秒

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

我想在单击按钮时创建小时、分钟和秒的倒计时器。这是我到目前为止的代码。

HTML 代码

<div class="colomn" style="margin-right: 20px">
<button class="start" onclick="clock();">Start</button>
</div>

JavaScript 函数

<script>
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 5;

function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
}
}
}
</script>

这很简单,不显示单独的小时、分钟和秒。我如何应用它来计算小时、分钟和秒。请帮助我。

最佳答案

工作代码:

<!DOCTYPE HTML>
<html>
<body>

<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>

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

function countdownTimeStart(){

var countDownDate = new Date("Sep 25, 2025 15:00:00").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 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 = 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);
}
</script>

</body>
</html>

关于单击开始按钮时的 JavaScript 倒计时器,显示小时、分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50041474/

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