背景
Swiper 在打包时,发现代码体积比较大,考虑到离线缓存机制在1M以内情况下,选择了造轮子。
源码
实现思路
1、利用flex设置滑动块的布局
2、利用transform:translateX 移动滑块、transition设置滑动效果
3、利用touch事件触发交互
flex设置滑动块的布局
设想可以自动计算滑块宽度、也可以自己设置显示几个滑块;
updateSlideStyles() {
this.wrapper!.style.display = 'flex';
if (this.options.slidesPerView === 'auto') {
this.slides.forEach(slide => {
slide.style.flex = '0 0 auto';
slide.style.marginRight = `${this.options.spaceBetween}px`;
});
} else {
const spaceBetween = (this.options.spaceBetween / this.container?.clientWidth * 100)
const slideWidth = (100 - spaceBetween * (this.options.slidesPerView - 1)) / this.options.slidesPerView;
this.slides.forEach(slide => {
slide.style.flex = `0 0 ${slideWidth}%`;
slide.style.marginRight = `${this.options.spaceBetween}px`;
});
}
}
计算移动偏移
当滑动到第二项时,translateX等于 第一项宽度 + spaceBetween设置的距离。同等第三项时,translateX 等于前面2项宽度 + 2个 spaceBetween设置的距离。
getOffset(index: number) {
return this.slides.slice(0, index).reduce((total, slide) => {
return total + slide.offsetWid