动画时钟图片切换的JavaScript实现涉及基础的前端开发概念,包括DOM操作、事件监听、定时器使用以及CSS动画。以下是详细解答:
setInterval
或setTimeout
函数用于周期性地执行代码。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animation Clock</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="clock">
<img id="clockImage" src="image1.jpg" alt="Clock Image">
</div>
<script src="script.js"></script>
</body>
</html>
#clock {
text-align: center;
margin-top: 50px;
}
#clockImage {
width: 200px;
height: 200px;
transition: opacity 1s ease-in-out;
}
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg']; // 图片数组
let currentIndex = 0;
function changeImage() {
const clockImage = document.getElementById('clockImage');
clockImage.style.opacity = 0; // 先淡出
setTimeout(() => {
clockImage.src = images[currentIndex]; // 切换图片
clockImage.style.opacity = 1; // 再淡入
currentIndex = (currentIndex + 1) % images.length; // 更新索引
}, 1000); // 等待淡出完成
}
setInterval(changeImage, 3000); // 每3秒切换一次图片
requestAnimationFrame
优化动画,确保代码高效运行。performance.now()
获取更精确的时间戳,或调整定时器间隔以适应实际需求。通过以上步骤和解决方案,可以有效实现一个动画时钟图片切换的功能。
领取专属 10元无门槛券
手把手带您无忧上云