JavaScriptだけでカルーセル実装

HTML

1
2
3
4
5
6
7
<div class="carousel">
  <ul>
    <li>swipe 1</li>
    <li>swipe 2</li>
    <li>swipe 3</li>
  </ul>
</div>

CSS

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
ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}
 
.carousel {
  overflow: hidden;
  width: 300px;
  height: 200px;
  margin: auto;
  background: #eee;
}
 
.carousel > ul {
  width: 900px;
  height: 200px;
}
 
.carousel > ul > li {
  float: left;
  width: 300px;
  height: 200px;
  padding: 10px;
  box-sizing: border-box;
}
 
.carousel > ul > li:nth-child(1) {
  background: #cff;
}
 
.carousel > ul > li:nth-child(2) {
  background: #ffc;
}
 
.carousel > ul > li:nth-child(3) {
  background: #fcf;
}
 
.carousel > ul {
  transition: transform 0.3s;
}
 
.carousel > ul.pos1 {
  transform: translateX(0);
}
 
.carousel > ul.pos2 {
  transform: translateX(-300px);
}
 
.carousel > ul.pos3 {
  transform: translateX(-600px);
}
 
.nav {
  width: 300px;
  margin: auto;
  text-align: center;
}
 
.nav > li {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin: 0 5px;
  border-radius: 50%;
  background: #ddd;
}
 
.nav > li.active {
  background: #999;
}

JavaScript

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
function setSwipe(elem) {
  var t = document.querySelector(elem);
  var tc = document.querySelector(elem + '> ul');
  var len = document.querySelectorAll(elem + '> ul > li').length;
  var startX;
  var startY;
  var moveX;
  var moveY;
  var dist = 30;
  var pos = 1;
  var nav = document.createElement('ul');
  nav.className = 'nav';
  for (var i = 0; i < len; i++) {
    var li = document.createElement('li');
    if (i === 0) {
      li.className = 'active';
    }
    nav.appendChild(li);
  }
  t.parentNode.insertBefore(nav, t.nextElementSibling);
  var navLi = document.querySelectorAll('.nav > li');
 
  t.addEventListener('touchstart', function(e) {
    e.preventDefault();
    startX = e.touches[0].pageX;
    startY = e.touches[0].pageY;
  });
 
  t.addEventListener('touchmove', function(e) {
    e.preventDefault();
    moveX = e.changedTouches[0].pageX;
    moveY = e.changedTouches[0].pageY;
  });
 
  t.addEventListener('touchend', function(e) {
    navLi[pos - 1].classList.remove('active');
    if (startX > moveX && startX > moveX + dist && pos < len) {
      pos++;
    } else if (startX < moveX && startX + dist < moveX && pos > 1) {
      pos--;
    }
    tc.className = 'pos' + pos;
    navLi[pos - 1].classList.add('active');
  });
}
setSwipe('.carousel');