我有以下 JavaScript 代码,当前在我的网页上显示数字时钟。我正在创建一个基于网络的交互式故事,该故事基于办公室的一天。每次用户单击按钮继续故事的下一部分时,我都希望将时钟增加 30 分钟。目前时钟仅显示实时时间。理想情况下,故事需要在上午 9:00 开始,然后随着用户的浏览而增加。
我完全不知道如何做到这一点,而且对 JavaScript 还很陌生,希望有人可以提供帮助!
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000); });
最佳答案
要在 09:00 点开始,您可以使用
var d = new Date();
d.setHours(9);
d.setMinutes(0);
d.setSeconds(0);
然后,我建议使用 moment.js
function onClick() {
d = moment(d).add(30, "minutes").toDate();
var el = document.getElementById('clock');
el.innerHTML = moment(d).format("HH:mm:ss");
}
您也可以不使用 moment.js 来实现
function pad(t) {
return t < 10 ? "0" + t : t;
}
function onClick() {
d.setMinutes(d.getMinutes() + 30);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = pad(h) + ":" + pad(m) + ":" + pad(s);
document.getElementById("clock").innerHTML = time;
}
关于javascript - 如何让 Javascript 时钟根据按钮点击而增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180627/