JS 轮播图箭头切换是一种常见的网页交互效果,用于在图片轮播展示时通过点击箭头来切换到上一张或下一张图片。
基础概念:
优势:
类型:
应用场景:
可能出现的问题及原因:
解决方法:
以下是一个简单的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.carousel {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-item {
min-width: 100%;
height: 100%;
}
.arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 24px;
cursor: pointer;
}
.arrow-left {
left: 10px;
}
.arrow-right {
right: 10px;
}
</style>
</head>
<body>
<div class="carousel">
<div class="arrow arrow-left" onclick="move(-1)"><</div>
<div class="carousel-inner" id="carouselInner">
<img src="image1.jpg" alt="" class="carousel-item">
<img src="image2.jpg" alt="" class="carousel-item">
<img src="image3.jpg" alt="" class="carousel-item">
</div>
<div class="arrow arrow-right" onclick="move(1)">></div>
</div>
<script>
let currentIndex = 0;
const carouselInner = document.getElementById('carouselInner');
const items = document.querySelectorAll('.carousel-item');
const totalItems = items.length;
function move(direction) {
currentIndex += direction;
if (currentIndex < 0) {
currentIndex = totalItems - 1;
} else if (currentIndex >= totalItems) {
currentIndex = 0;
}
updateCarousel();
}
function updateCarousel() {
const offset = -currentIndex * 100;
carouselInner.style.transform = `translateX(${offset}%)`;
}
</script>
</body>
</html>
在上述代码中:
领取专属 10元无门槛券
手把手带您无忧上云