JavaScript 左右轮播图是一种常见的网页动画效果,用于展示一系列图片或内容,并允许用户通过点击按钮或自动播放来切换显示的内容。
以下是一个简单的JavaScript左右轮播图的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图示例</title>
<style>
#carousel {
width: 600px;
overflow: hidden;
position: relative;
}
#carousel img {
width: 100%;
display: none;
}
#carousel img.active {
display: block;
}
.controls {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.prev, .next {
cursor: pointer;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
}
</style>
</head>
<body>
<div id="carousel">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<button class="controls prev">❮</button>
<button class="controls next">❯</button>
</div>
<script>
const carousel = document.getElementById('carousel');
const images = carousel.getElementsByTagName('img');
const prevBtn = carousel.querySelector('.prev');
const nextBtn = carousel.querySelector('.next');
let currentIndex = 0;
function showImage(index) {
for (let i = 0; i < images.length; i++) {
images[i].classList.remove('active');
}
images[index].classList.add('active');
}
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
});
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
});
</script>
</body>
</html>
通过以上方法,可以有效实现和维护一个功能完善的JavaScript左右轮播图。
领取专属 10元无门槛券
手把手带您无忧上云