手写轮播图(支持h5手指滑动切换),可无缝滚动
以下是一个简单的轮播图实现,支持H5中使用手指滑动切换图片,并且具有无缝滚动的效果。
HTML部分:
<div class="carousel">
<div class="carousel-inner">
<div class="carousel-item active"><img src="image1.jpg"></div>
<div class="carousel-item"><img src="image2.jpg"></div>
<div class="carousel-item"><img src="image3.jpg"></div>
<!-- 更多轮播项 -->
</div>
<div class="carousel-controls">
<button class="carousel-control-prev">Previous</button>
<button class="carousel-control-next">Next</button>
</div>
</div>
CSS部分:
.carousel {
overflow: hidden;
position: relative;
width: 100%;
}
.carousel-inner {
display: flex;
width: 300%; /* 假设有三张图片,每张图片宽度100% */
transition: transform 0.5s ease-in-out;
}
.carousel-item {
flex: 1 0 auto;
width: 100%;
}
.carousel-item img {
width: 100%;
height: auto;
}
.carousel-controls {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.carousel-control-prev, .carousel-control-next {
cursor: pointer;
}
JavaScript部分:
let carousel = document.querySelector('.carousel');
let inner = document.querySelector('.carousel-inner');
let items = document.querySelectorAll('.carousel-item');
let prevBtn = document.querySelector('.carousel-control-prev');
let nextBtn = document.querySelector('.carousel-control-next');
let currentIndex = 0;
function moveToSlide(direction) {
let nextIndex = currentIndex + direction;
if (nextIndex < 0) {
nextIndex = items.length - 1;
} else if (nextIndex >= items.length) {
nextIndex = 0;
}
inner.style.transform = `translateX(${-nextIndex * 100}%)`;
currentIndex = nextIndex;
}
prevBtn.addEventListener('click', function() {
moveToSlide(-1);
});
nextBtn.addEventListener('click', function() {
moveToSlide(1);
});
carousel.addEventListener('touchstart', function(e) {
touchStartX = e.touches[0].clientX;
});
carousel.addEventListener('touchmove', function(e) {
e.preventDefault(); // 防止页面滚动
touchEndX = e.touches[0].clientX;
if (touchEndX > touchStartX) {
moveToSlide(-1); // 向左滑动
} else {
moveToSlide(1); // 向右滑动
}
});
let touchStartX, touchEndX;
这段代
评论已关闭