gpt4 book ai didi

javascript - 达到目标时更改倒数计时器的外观?

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

我已经构建了一个简单的倒计时计时器,我想知道如何才能做到这样,一旦倒计时结束,我就可以将计时器更改为一个 div,告诉用户倒计时已完成?目前它只会像这样向倒计时添加底片:

倒计时:

[ 01 ][ 01 ][ 10 ][ 30 ]
days hours mins secs

一旦超过时间限制:

[ 00 ][ -01 ][ -10 ][ -30 ]
days hours mins secs

我什至不确定从哪里开始,但这是我的计时器在 HTML 中的设置方式

计时器 HTML:

<div class="timer">
<div><div id="d"></div>days</div>
<div><div id="h"></div>hours</div>
<div><div id="m"></div>min</div>
<div><div id="s"></div>sec</div>
</div>

和我的 JS 函数:

// vars for current year
var current = new Date();

//Your current year
var current_year = current.getFullYear();

//Next year
var next_year = current_year + 1;

// Date you will count down to
// You can change the 'current_year' to 'next year' as well if you were counting down to someing in 2016
var target_date = new Date("july 4, " + current_year).getTime();

// Vars for units of time
var days, hours, minutes, seconds;

// Get the elements that will hold the numbers.
var $days = document.getElementById("d");
var $hours = document.getElementById("h");
var $minutes = document.getElementById("m");
var $seconds = document.getElementById("s");

// Calculate the countdown clock and set the HTML.
function update() {
// Find the amount of "seconds" between now and target.
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;

// Do some time calcs
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;

hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;

minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);

// Format the number strings and put them in the elements.
$days.innerHTML = pad(days, 2);
$hours.innerHTML = pad(hours, 2);
$minutes.innerHTML = pad(minutes, 2);
$seconds.innerHTML = pad(seconds, 2);
}

// update the HTML
// or else your boxes will be blank
update();

// update every 1 second.
setInterval(update, 1000);


// If num has less than size digits, add enough 0s to the front.
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}

还有一个 codepen 进一步帮助解释。

我想我需要一些类似......

  • var 表示“已完成”
  • 一个函数说一旦 var 完成,就改变 timer 的类?

我真的不确定,如有任何帮助,我们将不胜感激!

最佳答案

在您的 update() 函数中,您只需要检查 seconds_left 是否 <= 0,并按照您的建议更新类。

我已经更新了你的code包括一个较短的测试计时器和一个类添加。

var seconds_left = (target_date - current_date) / 1000; // Unchanged

if ( seconds_left <= 0 ) {
// Change class here
var ele = document.getElementsByClassName('timer')[0];
ele.classList.add('completed');
}

关于javascript - 达到目标时更改倒数计时器的外观?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161837/

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