图片的左右切换
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button id="prevBtn">Previous</button>
<button id="nextBtn">Next</button>
.slider {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.slider img {
width: 100%;
height: auto;
display: none;
}
.slider img.active {
display: block;
}
<script type="text/javascript">
// 获取相关元素
var slider = document.querySelector('.slider');
var prevBtn = document.getElementById('prevBtn');
var nextBtn = document.getElementById('nextBtn');
var images = slider.getElementsByTagName('img');
var currentIndex = 0;
// 显示当前图片
function showImage(index) {
// 移除所有图片的active类
for (var i = 0; i < images.length; i++) {
images[i].classList.remove('active');
}
// 添加当前图片的active类
images[index].classList.add('active');
}
// 点击上一张按钮
prevBtn.addEventListener('click', function() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
showImage(currentIndex);
});
// 点击下一张按钮
nextBtn.addEventListener('click', function() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
showImage(currentIndex);
});
// 显示初始图片
showImage(currentIndex);
</script>