Skip to main content

Class

类是用于创建对象的模板。他们用代码封装数据以处理该数据。 JS 中的类建立在原型上,但也具有某些语法和语义未与 ES5 类相似语义共享。

Swiper 案例

/* eslint-disable consistent-this */
// 变量
const SPEED = 50;

class Swiper {
constructor(element, option) {
this.el = element && document.getElementsByClassName(element)[0];
// 默认参数:检查是否传了参数,如果传了参数将参数和默认参数合并
this.option = {
initialSlide: 0,
...option,
};
this.state = {
slideGrid: [], // 轮播数组的translate集合
initialTouch: {
clientX: 0,
clientY: 0,
},
distance: {
distanceX: 0,
distanceY: 0,
},
currentIndex: 0,
};
// 执行初始化
this.init();
}

init() {
this.eventsListen();
this.getData();
this.getAnimation();
}
// Event
eventsListen() {
const swiper = this;

swiper.el.addEventListener(
"touchstart",
this.touchStart.bind(swiper),
false
);
swiper.el.addEventListener("touchmove", this.touchMove.bind(swiper), false);
swiper.el.addEventListener("touchend", this.touchEnd.bind(swiper), false);
}
// Getter
getFetch() {}
getData() {
this.getSlideGrid();
}
getNode() {}
getStyle() {}
getAnimation() {
const swiper = this;
const el = swiper.el;

el.style.transition = "all 0.5s ease";
}
// Method
touchStart(e) {
e.stopPropagation();
const swiper = this;
const { clientY, clientX } = e.touches[0];

swiper.state.initialTouch = { clientX, clientY };
}
// 计算移动距离
calculateDistance = (touch) => {
const { initialTouch } = this.state;

return {
distanceY: touch.clientY - initialTouch.clientY,
distanceX: touch.clientX - initialTouch.clientX,
};
};
touchMove(e) {
e.stopPropagation();
const swiper = this;
const { distanceX, distanceY } = this.calculateDistance(e.touches[0]);

swiper.state.distance = { distanceX, distanceY };
}
touchEnd(e) {
e.stopPropagation();
const swiper = this;
const {
distance: { distanceX },
currentIndex,
} = swiper.state;

if (distanceX > 0) {
swiper.state.currentIndex = currentIndex - 1;
} else if (distanceX < 0) {
swiper.state.currentIndex = currentIndex + 1;
}

this.doTranslate(swiper.state.currentIndex);
}
// 获取所有轮播的translate值 并保存到数组 所有的轮播都是通过这个数组来实现的
getSlideGrid() {
const swiper = this;

const slideChildNodes = this.el.childNodes;
const arr = [];

for (let i = 0; i < slideChildNodes.length; i++) {
arr.push(slideChildNodes[i].offsetLeft);
}
swiper.state.slideGrid = arr;
}
// 执行动画
doTranslate(index) {
const swiper = this;
const el = swiper.el;
const { slideGrid } = swiper.state;

el.style.transform = `translate3d(-${slideGrid[index]}px, 0px,0px)`;
}
// Render
render() {}
}
export default Swiper;
const initSwiper = {
initialSlide: 0,
};

let swiper = new Swiper("swiper-wrapper", initSwiper);

<div className="swiper-wrapper">
<div>0</div>
<div>1</div>
<div>2</div>
</div>;

参考