JavaScript 相册循环播放主要涉及以下几个基础概念:
setInterval
或 setTimeout
函数来定时执行代码,实现动画效果。以下是一个简单的 JavaScript 相册循环播放示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery Loop</title>
<style>
#gallery {
width: 600px;
height: 400px;
overflow: hidden;
position: relative;
}
#gallery img {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
#gallery img.active {
opacity: 1;
}
</style>
</head>
<body>
<div id="gallery">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<script>
const gallery = document.getElementById('gallery');
const images = gallery.getElementsByTagName('img');
let currentIndex = 0;
function showNextImage() {
// Hide current image
images[currentIndex].classList.remove('active');
// Move to next image
currentIndex = (currentIndex + 1) % images.length;
// Show next image
images[currentIndex].classList.add('active');
}
// Set interval to change image every 3 seconds
setInterval(showNextImage, 3000);
</script>
</body>
</html>
loading="lazy"
属性。requestAnimationFrame
替代 setInterval
进行动画控制。通过以上方法,可以有效实现一个稳定且用户体验良好的 JavaScript 相册循环播放功能。
没有搜到相关的文章