gpt4 book ai didi

javascript - 显示多时钟

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

我想显示两个时钟,目前只有一个显示:

              <script type="text/javascript">
var tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function GetClock(){
var d=new Date();
var nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;

var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds();
if(nmin<=9) nmin="0"+nmin
if(nsec<=9) nsec="0"+nsec;

document.getElementById('clockbox').innerHTML=" "+ndate+" "+tmonth[nmonth]+" "+nyear+", "+nhour+":"+nmin+":"+nsec+"";
}

window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>

<div id="clockbox"></div>, <script type="text/javascript" src="js/rs-clock.js"></script>

第二个时钟 (rs-clock.js) 的脚本如下:

function startTime() {
var today=new Date();
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('rs-clock').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}

function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}

我是否必须将两者都制作成 .js 然后添加它,如果是,我该怎么做?

最佳答案

如果您希望出现多个时钟,那么您当前的解决方案存在一些问题。每个元素都需要有自己的实例,每个元素都需要是变量下的唯一对象。为此,我建议给时钟一个类名,然后在这些时钟上运行 for 循环以设置主时间功能。最后,因为它是一个时钟,所以我建议使用 setInterval 而不是 setTimeout,这样您就可以确保它每秒运行一次。这反过来当然可以很容易地更改为使用 i

上的 if 语句为一个特定实例添加天数、月数等
//make sure this is in some kind of onload function
elems = document.getElementsByClassName("clocks");
for (var i = 0; i < elems.length; i++) {
(function(i) { //this puts each set interval in its own unique instance
var temptime = elems[i]; //save the clock variable in this instance
setInterval(function() {
var today=new Date();
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
temptime.innerHTML = h+":"+m+":"+s;
}, 1000);
}(i));
}

一个有效的 jsfiddle:https://jsfiddle.net/krz2feqd/

我拿了你的第一个时钟并在 0 的唯一实例下将它实现到这个循环中。这是一个 jsfiddle:https://jsfiddle.net/pbp5scuL/

关于javascript - 显示多时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35202081/

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