前言
最近闲来无事,想看看Trae能不能帮我实现一下一款苹果风格的翻页时钟,用来展示时间,提示当前时间。
同时也可以展示倒计时,比如倒计时到某个时间点,比如倒计时到某个事件发生,比如倒计时到某个倒计时结束。最好是可以根据夜晚时间。
例如23:00-7:00,切换到深色主题,早上就自动展示浅色主题
看看最后的效果
深色主题 浅色主题

没有多说什么,trae就帮我完成了

首先是HTML结构,很简单,就是一个div,里面包含了时间和倒计时的元素,主要还是时分秒,不足10的在前面补0。

js代码是储存当前显示的时间,星期使用中文显示,更加通俗易懂
首先是初始化方法,初始化时间和日期显示,以及翻页卡片的元素。
js
function initClock() {
// 立即更新一次时钟
updateClock();
// 设置定时器,每秒更新一次
setInterval(updateClock, 1000);
}
然后是核心代码,就是更新时间的函数,每隔1秒调用一次,更新时间和倒计时,同时也更新日期显示,将翻页卡片进行翻转。
js
// 更新时钟显示
function updateClock() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 计算各个位的数字
const newTime = {
hoursTens: Math.floor(hours / 10),
hoursOnes: hours % 10,
minutesTens: Math.floor(minutes / 10),
minutesOnes: minutes % 10,
secondsTens: Math.floor(seconds / 10),
secondsOnes: seconds % 10
};
// 更新翻页卡片
updateFlipCard(hoursTens, currentTime.hoursTens, newTime.hoursTens);
updateFlipCard(hoursOnes, currentTime.hoursOnes, newTime.hoursOnes);
updateFlipCard(minutesTens, currentTime.minutesTens, newTime.minutesTens);
updateFlipCard(minutesOnes, currentTime.minutesOnes, newTime.minutesOnes);
updateFlipCard(secondsTens, currentTime.secondsTens, newTime.secondsTens);
updateFlipCard(secondsOnes, currentTime.secondsOnes, newTime.secondsOnes);
// 更新当前时间
currentTime = newTime;
// 更新日期显示
updateDateDisplay(now);
}
主题切换,根据时间切换主题,晚上切换到深色主题,早上切换到浅色主题,并且在切换主题时,添加过渡效果。
将其存储到本地缓存,只要你不去清理本地缓存,就会一直保持你切换的主题,下次刷新页面还是会在的。
js
// 主题切换
function switchTheme() {
const now = new Date();
const hours = now.getHours();
if (hours >= 23 || hours < 7) {
// 晚上切换到深色主题
document.body.classList.add('dark-theme');
} else {
// 早上切换到浅色主题
document.body.classList.remove('dark-theme');
}
}
日期显示,根据当前时间,展示当前的日期,格式为:2023年10月10日 星期一
js
// 更新日期显示
function updateDateDisplay(now) {
const dateDisplay = document.getElementById('date-display');
const dateString = now.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
weekday: 'long'
});
dateDisplay.textContent = dateString;
}
总结
1、通过Trae的代码,我们实现了一个苹果风格的翻页时钟,展示了当前时间和倒计时,并且根据时间切换了主题。
2、同时也实现了日期显示,根据当前时间,展示当前的日期,格式为:2023年10月10日 星期一
3、最后,我们也实现了主题切换,根据时间切换主题,晚上切换到深色主题,早上切换到浅色主题,并且在切换主题时,添加过渡效果,将其存储到本地缓存。