以下是关于手机端 JS 轮播图的相关信息:
基础概念: JS 轮播图是通过 JavaScript 实现的图片自动或手动切换展示的效果,常用于在有限的空间内展示多张图片。
优势:
类型:
应用场景:
常见问题及解决方法:
以下是一个简单的手机端 JS 轮播图示例代码:
HTML 结构:
<div class="carousel">
<div class="carousel-inner">
<img src="image1.jpg" alt="">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
</div>
<button class="prev">上一张</button>
<button class="next">下一张</button>
</div>
CSS 样式:
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 300px;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-inner img {
width: 100%;
height: auto;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
JavaScript 代码:
const carouselInner = document.querySelector('.carousel-inner');
const images = document.querySelectorAll('.carousel-inner img');
const prevButton = document.querySelector('.prev');
const nextButton = document.querySelector('.next');
let currentIndex = 0;
function showImage(index) {
const offset = -index * 100;
carouselInner.style.transform = `translateX(${offset}%)`;
}
prevButton.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
});
nextButton.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
});
// 自动轮播
setInterval(() => {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}, 3000);
领取专属 10元无门槛券
手把手带您无忧上云