Js实现wordclock
实现 Word Clock 的基本思路
Word Clock 是一种以文字显示时间的时钟,例如 "IT IS HALF PAST TEN"。实现这种时钟需要将时间转换为对应的单词组合。
时间转换为单词的逻辑
将时间分解为小时和分钟,根据分钟数选择对应的短语(如 "O'CLOCK"、"FIVE PAST"、"TEN TO" 等),再结合当前小时数生成完整的句子。例如 10:30 转换为 "IT IS HALF PAST TEN"。
HTML 结构设计
创建一个包含所有可能单词的网格布局,每个单词初始状态为隐藏。通过 JavaScript 动态显示当前时间对应的单词。
<div id="wordclock">
<span data-time="it">IT</span>
<span data-time="is">IS</span>
<span data-time="half">HALF</span>
<!-- 其他单词 -->
</div>
CSS 样式设置
设置网格布局,并控制单词的显示/隐藏状态。激活的单词可以高亮显示。
#wordclock {
display: grid;
grid-template-columns: repeat(11, 1fr);
gap: 5px;
}
#wordclock span {
opacity: 0.2;
}
#wordclock span.active {
opacity: 1;
font-weight: bold;
}
JavaScript 实现
编写时间转换函数,定期更新时间并激活对应的单词元素。
function updateWordClock() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = Math.floor(now.getMinutes() / 5) * 5;
// 清除所有激活状态
document.querySelectorAll('#wordclock span').forEach(span => {
span.classList.remove('active');
});
// 根据时间激活对应单词
const activeWords = getTimeWords(hours, minutes);
activeWords.forEach(word => {
document.querySelector(`span[data-time="${word}"]`).classList.add('active');
});
}
// 每5秒更新一次
setInterval(updateWordClock, 5000);
updateWordClock();
时间单词映射函数
创建将时间转换为单词数组的函数。
function getTimeWords(hours, minutes) {
const words = ['it', 'is'];
if (minutes === 0) {
words.push('oclock');
} else if (minutes === 5) {
words.push('five', 'past');
} else if (minutes === 10) {
words.push('ten', 'past');
} // 其他分钟情况...
words.push(getHourWord(hours));
return words;
}
function getHourWord(hour) {
const hourWords = ['twelve', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven'];
return hourWords[hour];
}
响应式设计考虑
添加媒体查询确保在不同屏幕尺寸下正常显示。
@media (max-width: 600px) {
#wordclock {
grid-template-columns: repeat(5, 1fr);
}
}
动画效果增强
可以添加过渡效果使单词激活更平滑。
#wordclock span {
transition: opacity 0.3s ease;
}
24小时制支持
如果需要支持24小时制,修改小时转换逻辑即可。
const hours = now.getHours(); // 直接使用24小时
本地化扩展
通过添加多语言映射对象,可以支持不同语言的Word Clock。
const timeWords = {
en: {
it: 'IT',
is: 'IS',
half: 'HALF'
// 其他英语单词
},
de: {
it: 'ES',
is: 'IST',
half: 'HALB'
// 其他德语单词
}
};
性能优化
使用requestAnimationFrame替代setInterval可以获得更流畅的动画效果。
function tick() {
updateWordClock();
requestAnimationFrame(tick);
}
tick();






