倒计时效果可以通过JavaScript的定时器 setInterval() 来实现。首先需要获取到倒计时结束的时间,然后通过每一秒钟减少一秒来实现倒计时效果。
以下是一个简单的倒计时效果的代码示例:
function countdown(endTime) {
let timer = setInterval(function() {
let nowTime = new Date().getTime();
let distance = endTime - nowTime;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("countdown").innerHTML = "倒计时:" + days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒 ";
if (distance < 0) {
clearInterval(timer);
document.getElementById("countdown").innerHTML = "倒计时已结束";
}
}, 1000);
}
// 倒计时结束时间为 2022年1月1日
let endTime = new Date("2022-01-01").getTime();
countdown(endTime);
时钟效果可以通过JavaScript的定时器 setInterval() 来实现。首先需要获取到当前的时间,然后通过每一秒钟更新一次来实现时钟效果。
以下是一个简单的时钟效果的代码示例:
function clock() {
let now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("clock").innerHTML = hours + ":" + minutes + ":" + seconds;
}
setInterval(clock, 1000);
其中,getHours()
、getMinutes()
和 getSeconds()
可以获取到当前时间的小时、分钟和秒数,setInterval()
可以每一秒钟更新一次时间显示。