用js和html实现闹钟
时间: 2023-11-27 10:49:35 浏览: 39
好的,以下是一个基本的 HTML 和 JavaScript 实现的闹钟:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>闹钟</title>
</head>
<body>
<h1>闹钟</h1>
<label for="time">设置时间:</label>
<input type="text" id="time" placeholder="HH:MM:SS">
<button onclick="setAlarm()">设置</button>
<br><br>
<label for="message">提示消息:</label>
<input type="text" id="message">
<br><br>
<button onclick="clearAlarm()">取消</button>
<script>
var alarmTimeout;
function setAlarm() {
var timeInput = document.getElementById('time');
var messageInput = document.getElementById('message');
var time = timeInput.value;
var message = messageInput.value;
if (time == "") {
alert("请输入时间!");
return;
}
var currentTime = new Date();
var hours = parseInt(time.split(":")[0]);
var minutes = parseInt(time.split(":")[1]);
var seconds = parseInt(time.split(":")[2]);
var alarmTime = new Date();
alarmTime.setHours(hours);
alarmTime.setMinutes(minutes);
alarmTime.setSeconds(seconds);
if (alarmTime < currentTime) {
alarmTime.setDate(alarmTime.getDate() + 1);
}
var timeRemaining = alarmTime.getTime() - currentTime.getTime();
alarmTimeout = setTimeout(function() {
alert(message);
}, timeRemaining);
}
function clearAlarm() {
clearTimeout(alarmTimeout);
}
</script>
</body>
</html>
```
这个闹钟页面由一个文本输入框和一个按钮组成,用来设置闹钟时间和提示消息。当用户点击“设置”按钮时,JavaScript 代码会解析输入的时间,计算出距离当前时间的时间差,然后使用 `setTimeout()` 函数来在指定的时间后弹出提示消息。用户也可以点击“取消”按钮来清除闹钟。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)