js实现闹钟
使用JavaScript实现闹钟功能
基础HTML结构
创建一个简单的HTML页面,包含时间显示和闹钟设置控件:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript闹钟</title>
<style>
#clock {
font-size: 48px;
margin: 20px;
}
.alarm-controls {
margin: 20px;
}
</style>
</head>
<body>
<div id="clock"></div>
<div class="alarm-controls">
<input type="time" id="alarmTime">
<button id="setAlarm">设置闹钟</button>
<button id="stopAlarm" disabled>停止闹铃</button>
</div>
<audio id="alarmSound" src="alarm.mp3" loop></audio>
</body>
</html>
JavaScript核心逻辑
// 获取DOM元素
const clockElement = document.getElementById('clock');
const alarmTimeInput = document.getElementById('alarmTime');
const setAlarmButton = document.getElementById('setAlarm');
const stopAlarmButton = document.getElementById('stopAlarm');
const alarmSound = document.getElementById('alarmSound');
// 更新时钟显示
function updateClock() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
clockElement.textContent = `${hours}:${minutes}:${seconds}`;
}
// 检查闹钟时间
function checkAlarm() {
const alarmTime = alarmTimeInput.value;
if (!alarmTime) return;
const now = new Date();
const currentHours = String(now.getHours()).padStart(2, '0');
const currentMinutes = String(now.getMinutes()).padStart(2, '0');
const currentTime = `${currentHours}:${currentMinutes}`;
if (currentTime === alarmTime) {
alarmSound.play();
stopAlarmButton.disabled = false;
}
}
// 事件监听
setAlarmButton.addEventListener('click', () => {
if (!alarmTimeInput.value) {
alert('请设置闹钟时间');
return;
}
alert(`闹钟已设置为 ${alarmTimeInput.value}`);
});
stopAlarmButton.addEventListener('click', () => {
alarmSound.pause();
alarmSound.currentTime = 0;
stopAlarmButton.disabled = true;
});
// 初始化
setInterval(() => {
updateClock();
checkAlarm();
}, 1000);
updateClock();
功能增强建议
添加多个闹钟功能:

const alarms = [];
function addAlarm(time) {
alarms.push(time);
renderAlarms();
}
function renderAlarms() {
const alarmsList = document.getElementById('alarmsList');
alarmsList.innerHTML = alarms.map(alarm => `
<div class="alarm-item">
<span>${alarm}</span>
<button onclick="removeAlarm('${alarm}')">删除</button>
</div>
`).join('');
}
添加闹钟重复选项:
<select id="alarmRepeat">
<option value="once">仅一次</option>
<option value="daily">每天</option>
<option value="weekdays">工作日</option>
</select>
注意事项
确保有有效的音频文件(如alarm.mp3)放在同一目录下 考虑使用Web Notification API在闹钟响起时显示桌面通知 对于移动端使用,需要添加适当的响应式设计 可以添加本地存储功能,保存用户设置的闹钟
这个实现提供了基本的闹钟功能,可以根据需要进一步扩展和完善。核心逻辑是通过定时器每秒检查当前时间是否与设定的闹钟时间匹配,匹配时触发音频播放。





