用js写出在不同的时间段(上午、下午和晚上)显示不同的图片和文字来问候。
时间: 2024-05-09 16:14:34 浏览: 8
好的,我可以帮你实现这个功能。你需要先确定你定义的时间段,比如上午是从早上6点到中午12点,下午是从中午12点到下午6点,晚上是从下午6点到早上6点。然后,你需要根据当前时间判断属于哪个时间段,从而显示相应的图片和文字。
下面是一个示例代码:
```javascript
// 获取当前时间
const now = new Date();
const hour = now.getHours();
// 定义时间段
const morning = [6, 7, 8, 9, 10, 11];
const afternoon = [12, 13, 14, 15, 16, 17];
const evening = [18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5];
// 判断当前时间属于哪个时间段
let message, image;
if (morning.includes(hour)) {
message = "早上好!";
image = "morning.jpg";
} else if (afternoon.includes(hour)) {
message = "下午好!";
image = "afternoon.jpg";
} else if (evening.includes(hour)) {
message = "晚上好!";
image = "evening.jpg";
}
// 显示图片和文字
const greeting = document.getElementById("greeting");
greeting.textContent = message;
const img = document.createElement("img");
img.src = image;
document.body.appendChild(img);
```
你可以根据自己的需求调整时间段和显示内容。希望能帮到你!