以下是一个使用JavaScript实现图片叠加滚动切换的简单示例代码:
一、HTML结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片叠加滚动切换</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="image-container">
<img src="image1.jpg" alt="图片1" class="active">
<img src="image2.jpg" alt="图片2">
<img src="image3.jpg" alt="图片3">
</div>
<script src="script.js"></script>
</body>
</html>
二、CSS样式(styles.css)
.image - container {
position: relative;
width: 800px;
height: 600px;
overflow: hidden;
}
.image - container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease - in - out;
}
.image - container img.active {
opacity: 1;
}
三、JavaScript代码(script.js)
const images = document.querySelectorAll('.image - container img');
let currentIndex = 0;
function showNextImage() {
// 移除当前图片的active类
images[currentIndex].classList.remove('active');
// 计算下一个图片的索引
currentIndex = (currentIndex + 1) % images.length;
// 添加active类到下一个图片
images[currentIndex].classList.add('active');
}
setInterval(showNextImage, 3000);
基础概念
img
标签的容器来放置要切换的图片。active
类)不透明外,其他图片透明度为0。transition
属性实现透明度的平滑过渡效果。currentIndex
来跟踪当前显示的图片索引。showNextImage
函数负责切换图片,先移除当前图片的active
类,计算下一个图片索引(循环显示),然后给下一个图片添加active
类。setInterval
每隔一定时间(这里是3秒)调用showNextImage
函数。优势
应用场景