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;
}
.buttons {
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="buttons prev" onclick="prevImage()">Prev</button>
<button class="buttons next" onclick="nextImage()">Next</button>
</div>
<script>
let currentIndex = 0;
const images = document.querySelectorAll('#carousel img');
const totalImages = images.length;
function showImage(index) {
images.forEach((img, i) => {
img.classList.remove('active');
});
images[index].classList.add('active');
}
function nextImage() {
currentIndex = (currentIndex + 1) % totalImages;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + totalImages) % totalImages;
showImage(currentIndex);
}
// 自动轮播
setInterval(nextImage, 3000);
</script>
</body>
</html>
通过以上方法,可以有效解决常见的图片轮播问题,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云