This repository has been archived by the owner on Nov 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjL.plugin.carousel.js
306 lines (288 loc) · 14.5 KB
/
jL.plugin.carousel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
* Carousel - плагин для реализации эффекта слайд-шоу
*
* Date 30.08.14
* Time 19:32
*
* @author Lossir [email protected]
* @version 2.1
*
* @augments jL
* @requires jL,jQuery
*/
;
(function (jL, $, undefined) {
jL.setPlugin('carousel', function (method, options) {
var settings = {
/**
* Родительское окно
* @type {HTMLElement|jQuery}
*
* @defaultValue this
*/
'window' : this,
/**
* Элементы перемещения
* @type {jQuery}
*/
items : this.find('>*'),
/**
* Функция, принимающая методы управления слайд-шоу
* @type {Function|null}
*
* @param {Object} control Объект содержит метода упраления слайд-шоу
*
* @defaultValue null
*/
callback : null,
/**
* Функция, определяющая способ смены слайдов
*
* @param {Number} prevItemsIndexStart Индекс первого элемента предыдущего показа
* @param {Number} currentItemsIndexStart Индекс первого элемента текущего показа
* @param {Array} prevItemsIndex Массив всех элементов прошлого показа
* @param {Array} currentItemsIndex Массив всех элементов текущего показа
* @param {Array} prevItemsIndexCut Массив уникальных элементов прошлого показ
* @param {Array} currentItemsIndexCut Массив уникальных элементов текущего показа
*/
replace : function (prevItemsIndexStart, currentItemsIndexStart, prevItemsIndex, currentItemsIndex, prevItemsIndexCut, currentItemsIndexCut) {
var speed = settings.speed,
animation = {},
orientation = settings.orientation == 'vertical'
? 'top'
: 'left';
switch (settings.style) {
case "all":
var widthItem = 100 / settings.limit;
settings.items.show().each(function (index) {
animation[orientation] = ((index - currentItemsIndexStart) * widthItem) + '%';
$(this).animate(animation,speed);
});
break;
case "now":
var items = settings.items.hide(),
hideShift = '-100%',
showShift = '100%';
if(prevItemsIndexStart>currentItemsIndexStart){
hideShift = '100%';
showShift = '-100%';
}
animation[orientation] = hideShift;
items.eq(prevItemsIndexStart).show().animate(animation, speed, function () {
$(this).hide()
});
animation[orientation] = '0%';
items.eq(currentItemsIndexStart).show().css(orientation, showShift).animate(animation, speed)
}
},
/**
* Цикличность
* @type {Boolean}
*
* @defaultValue true
*/
loop : true,
/**
* Автоматическая смена слайдов [в миллисекундах]
* @type {null|Number}
*
* @defaultValue null
*/
auto : null,
/**
* Стиль смены сладов
* @type {String} "now","all"
*
* @defaultValue "all"
*/
style : "all",
/**
* Скорость смены сладов
* @type {Number}
*
* @defaultValue 300
*/
speed : 300,
/**
* Класс, добавляемый показываемым слайдам
* @type {String|undefined}
*
* @defaultValue "selected"
*/
selected : "selected",
/**
* Ориентация движений horizontal || vertical
* @type {String}
*
* @defaultValue "horizontal"
*/
orientation: "horizontal",
/**
* Количество элементов, показываемых за раз
* @type {Number}
*
* @defaultValue 1
*/
limit : 1,
/**
* Количество элементов, сдвигаемых за раз
* @type {Number}
*
* @defaultValue 1
*/
shift : 1,
/**
* Порядковый номер слайда, первого в списке показываемых
* @type {Number}
*
* @defaultValue 0
*/
start : 0,
/**
* Элементы html на которые надо повешать события управления слайд-шоу
*/
controlBack : undefined,
controlForward: undefined,
controlDot : undefined
},
methods = {
/**
* Инициализация плагина
*/
init: function () {
var currentItemsIndex = [],
prevItemsIndex = [],
start = settings.start,
limit = settings.limit,
items = settings.items,
orientation = settings.orientation,
widthItem = 100 / limit,
/**
* Управление слайдами
*
* @param action {Number|String} ('-'|'+')
*/
control = function (action) {
var currentItemsIndexStart = currentItemsIndex[0] || 0,
prevItemsIndexStart = currentItemsIndexStart,
shift = items.length - settings.limit,
currentItemsIndexCut,
prevItemsIndexCut,
/**
* Добавляет класс выделенным пунктам
*/
selected = function () {
items.removeClass(settings.selected)
.eq(currentItemsIndexStart).addClass(settings.selected);
if (settings.controlDot) {
settings.controlDot.removeClass(settings.selected)
.eq(currentItemsIndexStart).addClass(settings.selected);
}
},
/**
* Определяет индекс первого элемента в текущем показе с учетом зацикливания
*
* @returns {Number}
*/
loopTest = function () {
if (currentItemsIndexStart > shift) {
return settings.loop && prevItemsIndexStart == shift
? 0
: shift;
}
else
if (currentItemsIndexStart < 0) {
return settings.loop && prevItemsIndexStart == 0
? shift
: 0;
}
else return currentItemsIndexStart;
};
/**
* Определяем как сдвигать элементы: по указанному индексу или в конкретную сторону
* Вычисляем индекс первого элемента в текущем показе
*/
if (/\d/.test(action)) {
if (action < shift) shift = action;
currentItemsIndexStart = shift;
}
else {
if (/(\+|\-)/.test(action)) {
currentItemsIndexStart += +(action + 1) > 0
? settings.shift
: -settings.shift;
currentItemsIndexStart = loopTest();
}
else return;
}
if (settings.selected)selected();
/* Если первый элемента не изменился - ничего не делаем */
if (currentItemsIndexStart == prevItemsIndexStart)return;
/* Определяем индексы всех элементов прошлого и текущего показа */
prevItemsIndex = currentItemsIndex;
currentItemsIndex = [];
for (var i = 0, j; i < limit; i++) {
j = currentItemsIndexStart + i;
currentItemsIndex.push(j);
}
/* Определяем индексы уникальных элементов прошлого и текущего показа */
currentItemsIndexCut = currentItemsIndex.diff(prevItemsIndex);
prevItemsIndexCut = prevItemsIndex.diff(currentItemsIndex);
settings.replace.call(items, prevItemsIndexStart, currentItemsIndexStart, prevItemsIndex, currentItemsIndex, prevItemsIndexCut, currentItemsIndexCut);
},
resize = function () {
items[orientation == 'vertical'
? 'height'
: 'width'](widthItem + '%');
items.each(function (index) {
$(this).css(orientation == 'vertical'
? 'top'
: 'left', index * (widthItem) + '%');
if (index >= start && index < start + limit) {
currentItemsIndex.push(index);
}
});
},
controlActionOn = function() {
var ready = true,
sett,
autoTimerId = 0,
test = function (action) {
/* Делаем проверку, чтобы вызовы событий смены слайдов не накладывались и не сбивались */
if (ready) {
control(action);
ready = false;
clearTimeout(sett);
if (settings.auto)autoTimer();
sett = setTimeout(function () {
ready = true;
}, settings.speed);
}
},
autoTimer = function () {
clearInterval(autoTimerId);
autoTimerId = setInterval(function () {
test('+');
}, settings.auto)
};
if (settings.controlBack) settings.controlBack.on('click', function () {
test('-')
});
if (settings.controlForward) settings.controlForward.on('click', function () {
test('+')
});
if (settings.controlDot) settings.controlDot.on('click', function () {
test($(this).index())
});
if (settings.auto)autoTimer();
test(start);
};
controlActionOn();
resize();
}
};
return $(this).each(function () {
jL.callMethodPlugin.call(this, methods, method, options, settings)
});
});
}(jL, jQuery));