Day28 純 JavaScript Slider (ft. CSS scroll-snap-type)

今天我們要來製作Slider效果。不過要用一個你應該沒有看過有人這樣做但卻很簡單的方法。

應用應該不用我多說,不管是公司網站展示產品,學校輪播榮譽榜,還是業界案例輪播介紹都會使用到slider。而我今天忙到晚上九點半才開始寫文章是因為白天在做這個心理測驗,左右滑動效果也是使用slider。

不過想到要定位、還要偵測各種滑鼠點擊、移動、手機點擊就十分麻煩。你寫 code 累 debug 累瀏覽器也累要一直監聽…歸剛欸…

這時 CSS 又出現了。向你介紹: scroll-snap-type

scroll-snap-type

這個屬性可以讓元素上下或左右滑動時一滑就是整頁。我覺得最讚的是可以在筆電上面的觸控板直接往右滾,而且因為是內建語法所以非常順暢。使用用法如下:

 1/* 不開 */
 2scroll-snap-type: none;
 3
 4/* 開 */
 5scroll-snap-type: x;
 6scroll-snap-type: y;
 7scroll-snap-type: block;
 8scroll-snap-type: inline;
 9scroll-snap-type: both;
10
11/* 縮寫,加上 強制 | 接近 設定 */
12/* mandatory | proximity */
13scroll-snap-type: x mandatory;
14scroll-snap-type: y proximity;
15scroll-snap-type: both mandatory;

建議設定成 mandatory比較能確保有被吸附到。

我的用法如下,外元素設定scroll-snap-type: x mandatory,內元素設定對齊位置 scroll-snap-align: center置中。完整版面如下:

 1<section>
 2  <div class="items">
 3    <button onclick="backward()"></button>
 4    <div>1</div>
 5    <div>2</div>
 6    <div>3</div>
 7    <div>4</div>
 8  </div>
 9  <button onclick="foward()"></button>
10</section>
 1* {
 2  padding: 0;
 3  margin: 0;
 4  box-sizing: border-box;
 5}
 6body {
 7  overflow: hidden;
 8}
 9section {
10  position: relative;
11}
12.items {
13  display: flex;
14  height: 400px;
15  width: 100%;
16  overflow: scroll;
17  scroll-snap-type: x mandatory;
18}
19.items div {
20  width: 100%;
21  height: 100%;
22  background: orange;
23  flex-shrink: 0;
24  display: flex;
25  align-items: center;
26  justify-content: center;
27  font-size: 3em;
28  scroll-snap-align: center;
29}
30.items div:nth-child(odd) {
31  background: lightblue;
32}
33button {
34  position: absolute;
35  top: 50%;
36  left: 1em;
37  transform: translate(-50%, -50%);
38  outline: transparent;
39  border: none;
40  background: transparent;
41  font-size: 3em;
42  transition: transform 0.3s;
43  cursor: pointer;
44}
45section button:last-child {
46  left: unset;
47  right: 1em;
48}
49section button:last-child:hover {
50  transform: translate(-20%, -50%);
51}
52section button:first-child:hover {
53  transform: translate(-80%, -50%);
54}

我還加上了往左右的按鈕,這樣用滑鼠點擊或是滑動,就這麼簡單。最後來加上 JavaScript,讓按鈕可以點擊。

JavaScript

先用變數用來追蹤當前顯示的圖片的索引。一開始它被設定為0,代表第一張圖片。

1let currentIndex = 0

接下來是往左右的函式。在滾動之前,它會檢查是否可以向前或向後查看圖片。如果可以,就會增加或減少 currentIndex,然後調用 scrollToCurrentIndex() 函式。

 1function backward() {
 2  if (currentIndex > 0) {
 3    currentIndex--;
 4    scrollToCurrentIndex();
 5  }
 6}
 7function foward() {
 8  if (currentIndex < itemDivs.length - 1) {
 9    currentIndex++;
10    scrollToCurrentIndex();
11  }
12}

來寫滾動的函式。它會計算當前圖片的寬度,然後根據 currentIndex 的值來滾動 itemsContainer 到正確的位置,使用平滑的滾動效果。然後它呼叫 hideButton() 函式來控制按鈕的可見度,讓按鈕在滾動到最左邊或最右邊時隱藏。

1function scrollToCurrentIndex() {
2  const itemWidth = itemDivs[currentIndex].offsetWidth;
3  const scrollPosition = itemWidth * currentIndex;
4  itemsContainer.scrollTo({
5    left: scrollPosition,
6    behavior: "smooth"
7  });
8  hideButton();
9}

來寫一個函式來控制按鈕的可見度。如果 currentIndex 為0,表示目前是第一張圖片。因為 false 是 0 所以我們直接把透明度設為 0+false,這樣可以少寫兩行 if else。如果 currentIndex 等於最後一張圖片的索引,就會隱藏向前按鈕。因為"是"第一章圖片是 true 所以加上 ! 變成 false,透明度就是 0+false=0。如果不是第一張圖片就是 true,透明度就是 0+true=1

1const hideButton = () => {
2  backwardButton.style.opacity = 0 + !(currentIndex === 0);
3  forwardButton.style.opacity = 0 + !(currentIndex === itemDivs.length - 1);
4};

對了如果用觸控板滾動也要確認一下位置,來正確顯示按鈕。

1itemsContainer.addEventListener("scroll", function () {
2  currentIndex = Math.round(
3    itemsContainer.scrollLeft / itemDivs[0].offsetWidth
4  );
5  hideButton();
6});

完整的 JavaScript 如下:

 1let currentIndex = 0;
 2const backwardButton = document.querySelector("button[onclick='backward()']");
 3const forwardButton = document.querySelector("button[onclick='foward()']");
 4const itemsContainer = document.querySelector(".items");
 5const itemDivs = document.querySelectorAll(".items div");
 6function backward() {
 7  if (currentIndex > 0) {
 8    currentIndex--;
 9    scrollToCurrentIndex();
10  }
11}
12function foward() {
13  if (currentIndex < itemDivs.length - 1) {
14    currentIndex++;
15    scrollToCurrentIndex();
16  }
17}
18const hideButton = () => {
19  backwardButton.style.opacity = 0 + !(currentIndex === 0);
20  forwardButton.style.opacity = 0 + !(currentIndex === itemDivs.length - 1);
21};
22function scrollToCurrentIndex() {
23  const itemWidth = itemDivs[currentIndex].offsetWidth;
24  const scrollPosition = itemWidth * currentIndex;
25  itemsContainer.scrollTo({
26    left: scrollPosition,
27    behavior: "smooth"
28  });
29  hideButton();
30}
31scrollToCurrentIndex();
32itemsContainer.addEventListener("scroll", function () {
33  currentIndex = Math.round(
34    itemsContainer.scrollLeft / itemDivs[0].offsetWidth
35  );
36  hideButton();
37});

成果

因為我今天是用桌機所以沒有觸控板給我滾。如果你不喜觀滾動條的話可以用 CSS 隱藏。

 1 /* Hide scrollbar for Chrome, Safari and Opera */
 2.example::-webkit-scrollbar {
 3 display: none;
 4}
 5
 6/* Hide scrollbar for IE, Edge and Firefox */
 7.example {
 8 -ms-overflow-style: none;  /* IE and Edge */
 9 scrollbar-width: none;  /* Firefox */
10} 

https://codepen.io/edit-mr/pen/dywrReK

成果

以上就是我今天的分享,我們使用少許的程式碼就做出這個性能十分不錯的陽春 slider。你可以再加上一點裝飾,比如在底下放上顯示當前圖片的小圓點,或是加上自動播放。如果你有興趣可以自己試試看,抓取個數、移動的距離、以及移動的函數上面都有提供。 也需這個系列出書之後就會提到呢! 歡迎在 InstagramGoogle 新聞追蹤毛哥EM資訊密技,也歡迎訂閱我新開的YouTube頻道:網棧

我是毛哥EM,讓我們明天再見。

Posts in this Series