有多种方法可以在不同时间显示不同图片,以下是完整的解决方案:
<!DOCTYPE html>
<html>
<head>
<style>
#time-image {
width: 400px;
height: 300px;
object-fit: cover;
border-radius: 10px;
}
</style>
</head>
<body>
<h2>根据时间显示不同图片</h2>
<img id="time-image" src="" alt="时间图片">
<script>
const timeImage = document.getElementById('time-image');
const hour = new Date().getHours();
let imageUrl;
// 根据时间段选择图片
if (hour >= 6 && hour < 12) {
imageUrl = 'images/morning.jpg'; // 早晨 6:00-11:59
} else if (hour >= 12 && hour < 18) {
imageUrl = 'images/afternoon.jpg'; // 下午 12:00-17:59
} else if (hour >= 18 && hour < 22) {
imageUrl = 'images/evening.jpg'; // 傍晚 18:00-21:59
} else {
imageUrl = 'images/night.jpg'; // 夜晚 22:00-5:59
}
timeImage.src = imageUrl;
timeImage.alt = `${hour}点显示的图片`;
</script>
</body>
</html>
<style>
.time-based-image {
width: 400px;
height: 300px;
background-size: cover;
background-position: center;
}
/* 通过data属性设置不同时间的背景图 */
.time-based-image[data-time="morning"] {
background-image: url('images/morning.jpg');
}
.time-based-image[data-time="afternoon"] {
background-image: url('images/afternoon.jpg');
}
.time-based-image[data-time="evening"] {
background-image: url('images/evening.jpg');
}
.time-based-image[data-time="night"] {
background-image: url('images/night.jpg');
}
</style>
<div id="time-container"></div>
<script>
const container = document.getElementById('time-container');
const hour = new Date().getHours();
let timePeriod;
if (hour >= 6 && hour < 12) timePeriod = 'morning';
else if (hour >= 12 && hour < 18) timePeriod = 'afternoon';
else if (hour >= 18 && hour < 22) timePeriod = 'evening';
else timePeriod = 'night';
container.innerHTML = ``;
</script>
<script>
function getTimeBasedImage() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const timeStr = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
// 定义时间范围和对应的图片
const timeSlots = [
{ start: '06:00', end: '08:59', image: 'sunrise.jpg', name: '日出' },
{ start: '09:00', end: '11:59', image: 'morning.jpg', name: '上午' },
{ start: '12:00', end: '13:59', image: 'noon.jpg', name: '中午' },
{ start: '14:00', end: '17:59', image: 'afternoon.jpg', name: '下午' },
{ start: '18:00', end: '19:29', image: 'sunset.jpg', name: '日落' },
{ start: '19:30', end: '23:59', image: 'night.jpg', name: '夜晚' },
{ start: '00:00', end: '05:59', image: 'midnight.jpg', name: '深夜' }
];
// 查找当前时间对应的时段
for (const slot of timeSlots) {
if (timeStr >= slot.start && timeStr <= slot.end) {
return slot;
}
}
// 默认返回
return { image: 'default.jpg', name: '默认' };
}
// 使用
const currentSlot = getTimeBasedImage();
document.getElementById('myImage').src = `images/${currentSlot.image}`;
document.getElementById('time-info').textContent = `当前时段: ${currentSlot.name}`;
</script>
<script>
function getSeasonalImage() {
const now = new Date();
const month = now.getMonth() + 1; // 1-12月
let season, image;
// 判断季节(北半球)
if (month >= 3 && month <= 5) {
season = '春季';
image = 'spring.jpg';
} else if (month >= 6 && month <= 8) {
season = '夏季';
image = 'summer.jpg';
} else if (month >= 9 && month <= 11) {
season = '秋季';
image = 'autumn.jpg';
} else {
season = '冬季';
image = 'winter.jpg';
}
return { season, image };
}
const seasonInfo = getSeasonalImage();
document.write(`
<img src="images/${seasonInfo.image}" alt="${seasonInfo.season}图片">
<p>当前季节: ${seasonInfo.season}</p>
`);
</script>
<script>
const weekdayImages = [
'monday.jpg', // 0: 星期日
'tuesday.jpg', // 1: 星期一
'wednesday.jpg', // 2: 星期二
'thursday.jpg', // 3: 星期三
'friday.jpg', // 4: 星期四
'saturday.jpg', // 5: 星期五
'sunday.jpg' // 6: 星期六
];
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
const today = new Date().getDay(); // 0-6
document.getElementById('daily-image').src = `images/${weekdayImages[today]}`;
document.getElementById('weekday').textContent = `星期${weekdays[today]}`;
</script>
<!DOCTYPE html>
<html>
<head>
<title>智能时间图片展示</title>
<style>
.image-container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
text-align: center;
background: #f8f9fa;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.time-image {
width: 100%;
max-height: 400px;
object-fit: cover;
border-radius: 8px;
margin: 20px 0;
transition: opacity 0.5s ease;
}
.info-panel {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
margin-top: 20px;
padding: 15px;
background: white;
border-radius: 8px;
}
.time-card {
padding: 10px;
min-width: 120px;
}
.time-value {
font-size: 24px;
font-weight: bold;
color: #3498db;
}
.time-label {
font-size: 14px;
color: #666;
}
</style>
</head>
<body>
<div class="image-container">
<h1>🌅 智能时间图片展示</h1>
<img id="dynamicImage" class="time-image" src="" alt="动态图片">
<div class="info-panel">
<div class="time-card">
<div class="time-value" id="currentTime">--:--</div>
<div class="time-label">当前时间</div>
</div>
<div class="time-card">
<div class="time-value" id="timePeriod">--</div>
<div class="time-label">时段</div>
</div>
<div class="time-card">
<div class="time-value" id="currentSeason">--</div>
<div class="time-label">季节</div>
</div>
<div class="time-card">
<div class="time-value" id="currentWeekday">--</div>
<div class="time-label">星期</div>
</div>
</div>
<p id="imageDescription">正在加载时间信息...</p>
</div>
<script>
// 图片配置
const imageConfig = {
// 按时间段
timeOfDay: {
morning: {
image: 'https://images.unsplash.com/photo-1498496294614-acc6335f7a3a?w=800',
name: '早晨',
hours: [6, 7, 8, 9, 10, 11]
},
afternoon: {
image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w-800',
name: '下午',
hours: [12, 13, 14, 15, 16, 17]
},
evening: {
image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800',
name: '傍晚',
hours: [18, 19, 20, 21]
},
night: {
image: 'https://images.unsplash.com/photo-1534088568595-a066f410bcda?w=800',
name: '夜晚',
hours: [22, 23, 0, 1, 2, 3, 4, 5]
}
},
// 按季节
seasons: {
spring: {
image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800',
name: '春季',
months: [3, 4, 5]
},
summer: {
image: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=800',
name: '夏季',
months: [6, 7, 8]
},
autumn: {
image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800',
name: '秋季',
months: [9, 10, 11]
},
winter: {
image: 'https://images.unsplash.com/photo-1483664852095-d6cc6870702d?w=800',
name: '冬季',
months: [12, 1, 2]
}
},
// 按星期(备用)
weekdays: [
{ image: 'sunday.jpg', name: '星期日' },
{ image: 'monday.jpg', name: '星期一' },
{ image: 'tuesday.jpg', name: '星期二' },
{ image: 'wednesday.jpg', name: '星期三' },
{ image: 'thursday.jpg', name: '星期四' },
{ image: 'friday.jpg', name: '星期五' },
{ image: 'saturday.jpg', name: '星期六' }
]
};
// 获取当前时间信息
function getCurrentTimeInfo() {
const now = new Date();
const hour = now.getHours();
const month = now.getMonth() + 1;
const weekday = now.getDay();
return { hour, month, weekday, now };
}
// 获取时间段
function getTimePeriod(hour) {
for (const [period, config] of Object.entries(imageConfig.timeOfDay)) {
if (config.hours.includes(hour)) {
return { period, name: config.name, image: config.image };
}
}
return { period: 'default', name: '默认', image: 'default.jpg' };
}
// 获取季节
function getSeason(month) {
for (const [season, config] of Object.entries(imageConfig.seasons)) {
if (config.months.includes(month)) {
return { season, name: config.name, image: config.image };
}
}
return { season: 'default', name: '默认', image: 'default.jpg' };
}
// 获取星期名称
function getWeekdayName(weekday) {
const names = ['日', '一', '二', '三', '四', '五', '六'];
return `星期${names[weekday]}`;
}
// 更新页面
function updatePage() {
const { hour, month, weekday, now } = getCurrentTimeInfo();
const timePeriod = getTimePeriod(hour);
const season = getSeason(month);
const weekdayName = getWeekdayName(weekday);
// 更新时间显示
const timeString = now.toLocaleTimeString('zh-CN');
document.getElementById('currentTime').textContent = timeString;
document.getElementById('timePeriod').textContent = timePeriod.name;
document.getElementById('currentSeason').textContent = season.name;
document.getElementById('currentWeekday').textContent = weekdayName;
// 更新图片(这里使用时间段图片,你也可以改为季节图片)
const imageElement = document.getElementById('dynamicImage');
imageElement.src = timePeriod.image;
imageElement.alt = `${timePeriod.name}图片`;
// 更新描述
document.getElementById('imageDescription').textContent =
`现在是${season.name}的${timePeriod.name},${weekdayName} ${timeString}`;
}
// 初始加载
updatePage();
// 每分钟更新一次
setInterval(updatePage, 60000);
// 添加图片加载错误处理
document.getElementById('dynamicImage').onerror = function() {
this.src = 'https://images.unsplash.com/photo-1541701494587-cb58502866ab?w=800';
this.alt = '默认图片';
};
</script>
</body>
</html>
<script>
function getDailyImage() {
const today = new Date().toDateString(); // "Mon Jan 20 2025"
const cached = localStorage.getItem('dailyImage');
if (cached) {
const { date, image } = JSON.parse(cached);
if (date === today) {
return image; // 使用缓存的图片
}
}
// 获取新图片(可以从API或数组随机选择)
const dailyImages = ['day1.jpg', 'day2.jpg', 'day3.jpg'];
const randomImage = dailyImages[Math.floor(Math.random() * dailyImages.length)];
// 缓存到本地存储
localStorage.setItem('dailyImage', JSON.stringify({
date: today,
image: randomImage
}));
return randomImage;
}
document.getElementById('daily-pic').src = `images/${getDailyImage()}`;
</script>
<?php
// 根据时间返回不同图片
$hour = date('H');
$image = 'default.jpg';
if ($hour >= 6 && $hour < 12) {
$image = 'morning.jpg';
} elseif ($hour >= 12 && $hour < 18) {
$image = 'afternoon.jpg';
} elseif ($hour >= 18 && $hour < 22) {
$image = 'evening.jpg';
} else {
$image = 'night.jpg';
}
?>
<img src="images/<?php echo $image; ?>" alt="时间图片">
<p>当前时间: <?php echo date('H:i'); ?></p>
图片预加载避免切换时闪烁:
// 预加载所有可能用到的图片
const images = ['morning.jpg', 'afternoon.jpg', 'evening.jpg', 'night.jpg'];
images.forEach(src => {
const img = new Image();
img.src = `images/${src}`;
});
使用过渡动画:
.time-image {
transition: opacity 0.5s ease;
}
.fade-out {
opacity: 0;
}
.fade-in {
opacity: 1;
}
提供默认图片:
imageElement.onerror = function() {
this.src = 'images/default.jpg';
};
<img id="timeImage" src="" alt="">
<script>
const hour = new Date().getHours();
const img = document.getElementById('timeImage');
if (hour < 12) img.src = 'morning.jpg';
else if (hour < 18) img.src = 'afternoon.jpg';
else img.src = 'night.jpg';
</script>
关键点:使用 JavaScript 获取当前时间,根据时间条件设置不同的图片路径。