gpt4 book ai didi

javascript - 多个 "clocks"的倒计时JavaScript

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

我需要在一页上创建多个倒计时时钟。目前我只有一个,但我想让脚本变得漂亮和紧凑,所以我想对日期使用相同的计算,但只是提取不同的值。

英联邦运动会开始倒计时。我需要另一个倒计时闭幕式仪式。

脚本:

// set the date we're counting down to
var target_date_opening = new Date("Jul 23, 2014").getTime();
var target_date_closing = new Date("Aug 23, 2014").getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdownOpening = document.getElementById("countdownOpening");
var countdownClosing = document.getElementById("countdownClosing");

// update the tag with id "countdownOpening" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date_opening - current_date) / 1000;

// do some time calculations
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 countdown string + set tag value
countdownOpening.innerHTML = days + " days " + hours + " hours "
+ minutes + " minutes " + seconds + " seconds";

}, 1000);

您可以看到我创建了新变量来区分目标日期 (target_date_ending)

我有 innerHTML 的 ID 作为 countdownClosing。

我的问题是让 setInterval 函数计算 target_date_ending 并输出 countdownClosing ,而无需再次复制脚本。

我不确定是否需要单独的变量来存储分钟小时变量。

最佳答案

尝试

// set the date we're counting down to
var target_date_opening = new Date("Jul 23, 2014").getTime();
var target_date_closing = new Date("Aug 23, 2014").getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdownOpening = document.getElementById("countdownOpening");
var countdownClosing = document.getElementById("countdownClosing");

// update the tag with id "countdownOpening" every 1 second
setInterval(function () {
print(countdownOpening, target_date_opening)
print(countdownClosing, target_date_closing)
}, 1000);

function print(el, time) {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (time - current_date) / 1000;

// do some time calculations
var days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;

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

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

// format countdown string + set tag value
el.innerHTML = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds";
}

演示:Fiddle

关于javascript - 多个 "clocks"的倒计时JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21379425/

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