html结构: ul#selector > li > img
js: 改 es6 class写法
class Swiper {
constructor() {
this.transition = "-webkit-transition: -webkit-transform .3s ease";
this.css = [
"z-index: 3; -webkit-transform: translate3d(0, 0, 10px) scale3d(1, 1, 1); visibility: visible;",
"z-index: 2; -webkit-transform: translate3d(" + this.rem(-148) + ", 0, 6px) scale3d(.8, .8, 1); visibility: visible;",
"z-index: 2; -webkit-transform: translate3d(" + this.rem(148) + ", 0, 6px) scale3d(.8, .8, 1); visibility: visible;",
"z-index: 1; -webkit-transform: translate3d(" + this.rem(-240) + ", 0, 2px) scale3d(.667, .667, 1); visibility: visible;",
"z-index: 1; -webkit-transform: translate3d(" + this.rem(240) + ", 0, 2px) scale3d(.667, .667, 1); visibility: visible;"
];
this.x0 = null;
this.y0 = null;
this.hasmoved = 0;
this.lock = 0;
this.container = null;
this.item = [];
this.visual = [];
this.queue = [];
return this;
}
touchstartHandle(e) {
var touch = e.targetTouches[0], x = touch.pageX, y = touch.pageY;
this.x0 = x;
this.y0 = y;
this.hasmoved = 0;
this.lock = 0;
}
touchmoveHandle(e) {
if(this.lock) return ;
var touch = e.targetTouches[0], x = touch.pageX, y = touch.pageY, offsetX = this.x0 - x, offsetY = this.y0 - y;
// 阻止滚动
this.hasmoved || (this.hasmoved = 1, Math.abs(offsetX) > Math.abs(offsetY) && e.preventDefault());
if(offsetX <= -50) {
// 向右
this.queue.unshift(this.queue.pop());
this.lock = 1;
this.swap();
} else if(offsetX >= 50) {
// 向左
this.queue.push(this.queue.shift());
this.lock = 1;
this.swap();
}
}
swap(withoutTransition) {
var queue = [].concat(this.queue),
count = 0,
len = this.visual.length,
visual = new Array(len),
odd = 1;
// 提取前三个元素与后三个元素
while(count<5 && queue.length>0) {
visual[odd ? queue.shift() : queue.pop()] = this.css[count++] + (withoutTransition ? "" : this.transition);
odd = !odd; // 取反
}
// 对比一下数组
for(var i=0; i<len; ++i) {
visual[i] != this.visual[i] && (
this.visual[i] = visual[i],
this.item[i].style.cssText = this.visual[i] || "visibility: hidden"
);
}
}
rem(px) {
return px / 40 + "rem";
}
init(selector) {
const list = document.querySelector(selector);
list ? this.createSwiper(list) : console.log(selector + " undefined");
}
createSwiper(list) {
this.container = list;
list.style["-webkit-transform-style"] = "preserve-3d";
this.item = list.querySelectorAll("li");
for(var i=0; i<this.item.length; ++i) {
this.item[i].style.visibility = "hidden"
}
this.queue = Array.from({length: this.item.length}, (v, i) => i)
this.visual = new Array(this.item.length); // 与 item 做对应的虚拟DOM
this.swap("without transition"); // 初始排版
if(this.item.length <= 1) return ;
this.container.addEventListener("touchstart", this.touchstartHandle.bind(this), false);
this.container.addEventListener("touchmove", this.touchmoveHandle.bind(this), false);
}
}
调用: const swiper = new Swiper(); swiper.init("#selector")
如果想直接调用不实例的话 直接给构造方法里的返回就行 return this.init(selector) , 调用: new Swiper('#selector')