-
Notifications
You must be signed in to change notification settings - Fork 0
/
carousel.html
63 lines (53 loc) · 2.23 KB
/
carousel.html
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
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="carousel.css">
</head>
<body>
<div id="carousel" class="carousel">
<button class="arrow prev">⇦</button>
<div class="gallery" id="divGallery">
<ul class="images" id="ulImages">
<li><img src="https://en.js.cx/carousel/1.png"></li>
<li><img src="https://en.js.cx/carousel/2.png"></li>
<li><img src="https://en.js.cx/carousel/3.png"></li>
<li><img src="https://en.js.cx/carousel/4.png"></li>
<li><img src="https://en.js.cx/carousel/5.png"></li>
<li><img src="https://en.js.cx/carousel/6.png"></li>
<li><img src="https://en.js.cx/carousel/7.png"></li>
<li><img src="https://en.js.cx/carousel/8.png"></li>
<li><img src="https://en.js.cx/carousel/9.png"></li>
<li><img src="https://en.js.cx/carousel/10.png"></li>
</ul>
</div>
<button class="arrow next">⇨</button>
</div>
<script>
let prevIndex = 0;
let totalImages = ulImages.getElementsByTagName('LI').length;
let buttons = document.querySelectorAll('.arrow');
let nxtBtnindex = buttons[0].classList.contains('next') ? 0 : 1;
let preBtnindex = buttons[0].classList.contains('prev') ? 0 : 1;
let prevBtn = buttons[preBtnindex], nextBtn = buttons[nxtBtnindex];
buttons.forEach(btn => btn.onclick = onBtnClick);
function onBtnClick() {
let isNext = this.classList.contains('next');
if (isNext && prevBtn.disabled)
prevBtn.disabled = false;
if (!isNext && nextBtn.disabled)
nextBtn.disabled = false;
let nextIndex = isNext ? (prevIndex + 3) : prevIndex - 3;
nextIndex = Math.max(0, nextIndex);
nextIndex = Math.min(totalImages - 3, nextIndex);
if (nextIndex === prevIndex) {
this.disabled = true;
return;
}
else {
ulImages.style.marginLeft = (0 - nextIndex * 130) + 'px';
prevIndex = nextIndex;
}
}
</script>
</body>
</html>