js实现swiper
使用原生JavaScript实现Swiper
通过原生JavaScript实现滑动轮播效果,核心逻辑包括DOM操作、事件监听和CSS过渡动画。以下是一个基础实现方案:
// 获取DOM元素
const swiperContainer = document.querySelector('.swiper-container');
const slides = document.querySelectorAll('.swiper-slide');
const prevBtn = document.querySelector('.swiper-button-prev');
const nextBtn = document.querySelector('.swiper-button-next');
// 初始化变量
let currentIndex = 0;
const slideCount = slides.length;
// 设置初始位置
function updateSlidePosition() {
slides.forEach((slide, index) => {
slide.style.transform = `translateX(${100 * (index - currentIndex)}%)`;
});
}
// 切换到指定幻灯片
function goToSlide(index) {
currentIndex = (index + slideCount) % slideCount;
updateSlidePosition();
}
// 事件监听
nextBtn.addEventListener('click', () => goToSlide(currentIndex + 1));
prevBtn.addEventListener('click', () => goToSlide(currentIndex - 1));
// 初始化
updateSlidePosition();
添加CSS样式
配合JavaScript实现,需要基础CSS样式支持:
.swiper-container {
position: relative;
overflow: hidden;
width: 100%;
}
.swiper-slide {
position: absolute;
width: 100%;
transition: transform 0.5s ease;
}
.swiper-button-prev,
.swiper-button-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 10;
}
添加触摸支持
为移动端添加触摸事件支持:
let touchStartX = 0;
let touchEndX = 0;
swiperContainer.addEventListener('touchstart', (e) => {
touchStartX = e.changedTouches[0].screenX;
});
swiperContainer.addEventListener('touchend', (e) => {
touchEndX = e.changedTouches[0].screenX;
handleSwipe();
});
function handleSwipe() {
const threshold = 50;
if (touchEndX < touchStartX - threshold) {
goToSlide(currentIndex + 1);
}
if (touchEndX > touchStartX + threshold) {
goToSlide(currentIndex - 1);
}
}
自动轮播功能
实现定时自动切换功能:
let autoPlayInterval;
function startAutoPlay(interval = 3000) {
autoPlayInterval = setInterval(() => {
goToSlide(currentIndex + 1);
}, interval);
}
function stopAutoPlay() {
clearInterval(autoPlayInterval);
}
// 鼠标悬停时暂停
swiperContainer.addEventListener('mouseenter', stopAutoPlay);
swiperContainer.addEventListener('mouseleave', () => startAutoPlay());
使用Swiper.js库
对于更复杂的需求,推荐使用专业的Swiper.js库:
-
安装Swiper.js
npm install swiper -
基础实现代码
import Swiper from 'swiper'; import 'swiper/css';
const mySwiper = new Swiper('.swiper-container', { loop: true, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, pagination: { el: '.swiper-pagination', }, autoplay: { delay: 3000, }, });
3. 对应HTML结构
```html
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>






