1
+ /**
2
+ * @method
3
+ * @param {function } cb
4
+ * @return {array }
5
+ */
6
+ NodeList . prototype . filter = function ( cb ) {
7
+
8
+ if ( typeof cb === 'function' ) {
9
+ let res = [ ]
10
+ for ( let i = 0 ; i < this . length ; i ++ ) {
11
+ if ( cb ( this [ i ] ) ) {
12
+ res . push ( this [ i ] )
13
+ }
14
+ }
15
+ return res
16
+ }
17
+ return this
18
+ }
19
+
20
+ const defaultConfig = {
21
+ direction : 'x' , // x | y
22
+ delay : 500
23
+ }
24
+
25
+ class Swiper {
26
+ constructor ( $container , config ) {
27
+ // init reference
28
+ this . contianer = $container
29
+ this . config = Object . assign ( { } , defaultConfig , config )
30
+ this . pages = this . contianer . childNodes . filter ( node => {
31
+ return node . nodeType === 1
32
+ } )
33
+ // init page index
34
+ this . index = 1
35
+ this . length = this . pages . length
36
+
37
+ // intervalID hold
38
+ this . interval = null
39
+
40
+ // init styles
41
+ this . contianer . style . cssText += `position: relative; transform: translate3d(0, 0, 0); transition: all ${ this . config . delay } ms ease 0s; `
42
+ this . pages . forEach ( ( page , idx ) => {
43
+ page . style . cssText +=
44
+ this . config . direction === 'y' ?
45
+ `position: absolute; top: ${ idx * 100 } %; left: 0px;` :
46
+ `position: absolute; top: 0px; left: ${ idx * 100 } %;`
47
+ } )
48
+ }
49
+
50
+ to ( index ) {
51
+ // adjust
52
+ if ( index > this . length ) index = this . length
53
+ if ( index < 1 ) index = 1
54
+ // cancel last slide
55
+ if ( this . interval ) clearInterval ( this . interval )
56
+
57
+ // toNext
58
+ if ( index > this . index ) {
59
+ this . interval = setInterval ( ( ) => {
60
+ if ( index > this . index ) {
61
+ this . contianer . style . cssText +=
62
+ this . config . direction === 'y' ?
63
+ `transform: translate3d(0px, -${ this . index * 100 } %, 0px);` :
64
+ `transform: translate3d(-${ this . index * 100 } %, 0px, 0px);`
65
+ this . index ++
66
+ } else {
67
+ clearInterval ( this . interval )
68
+ }
69
+ } , this . config . delay )
70
+ }
71
+ // toPrevious
72
+ else if ( index < this . index ) {
73
+ this . interval = setInterval ( ( ) => {
74
+ if ( index < this . index ) {
75
+ this . index --
76
+ this . contianer . style . cssText +=
77
+ this . config . direction === 'y' ?
78
+ `transform: translate3d(0px, -${ ( this . index - 1 ) * 100 } %, 0px);` :
79
+ `transform: translate3d(-${ ( this . index - 1 ) * 100 } %, 0px, 0px);`
80
+ } else {
81
+ clearInterval ( this . interval )
82
+ }
83
+ } , this . config . delay )
84
+ }
85
+ }
86
+
87
+ toNext ( ) {
88
+ this . to ( ++ this . index )
89
+ }
90
+
91
+ toPrevious ( ) {
92
+ this . to ( -- this . index )
93
+ }
94
+
95
+ toFirst ( ) {
96
+ this . to ( 1 )
97
+ }
98
+
99
+ toLast ( ) {
100
+ this . to ( this . length )
101
+ }
102
+ }
103
+
104
+ exports = Swiper
0 commit comments