Navigate back to the homepage

Day13: Slide in on Scroll

JavaScript30
July 7th, 2021 · 1 min read

專案介紹: 滾動視窗到定點時動畫滑入圖片的效果。

作品頁面:https://iris1114.github.io/javascript30/13_Slide-in-on-Scroll/

code

1//在一定時間20秒內只能觸發一次。
2function debounce(func, wait = 20, immediate = true) {
3 var timeout;
4 return function() {
5 var context = this,
6 args = arguments;
7 var later = function() {
8 timeout = null;
9 if (!immediate) func.apply(context, args);
10 };
11 var callNow = immediate && !timeout;
12 clearTimeout(timeout);
13 timeout = setTimeout(later, wait);
14 if (callNow) func.apply(context, args);
15 };
16}
17
18//頁面滾到指定高度時,讓圖片滑入、滑出文章
19
20function checkSlide() {
21 sliderImages.forEach((sliderImage) => {
22 //頁面已滾動距離 + 螢幕高度 - 圖片一半的高度 = 圖片滑入文章的高度
23 const slideInAt =
24 window.scrollY + window.innerHeight - sliderImage.height / 2;
25
26 //圖片至螢幕頂端的距離 + 圖片的高度 = 圖片底部至螢幕頂端的距離
27 const imageBottom = sliderImage.offsetTop + sliderImage.height;
28
29 //判斷是否已達圖片應滑入高度,即圖片滑入文章的高度 > 圖片至螢幕頂端的距離
30 const isHalfShown = slideInAt > sliderImage.offsetTop;
31
32 //判斷是否未達圖片應滑出高度,即頁面已滾動距離 < 圖片底部至螢幕頂端的距離
33 const isNotScrolledPast = window.scrollY < imageBottom;
34
35 //如果已達圖片應滑入高度,且未達圖片應滑出高度,就加上 `active` 樣式
36 if (isHalfShown && isNotScrolledPast) {
37 sliderImage.classList.add("active");
38 } else {
39 sliderImage.classList.remove("active");
40 }
41 });
42}
43
44const sliderImages = document.querySelectorAll(".slide-in");
45
46window.addEventListener("scroll", debounce(checkSlide));

補充

Window.scrollY

垂直方向已滚动的像素值。

Window.innerHeight

瀏覽器窗口的視口(viewport)高度(以像素為單位);如果有水平滾動條,也包括滾動條高度。

HTMLElement.offsetTop

HTMLElement.offsetTop 為只讀屬性,它返回當前元素相對於其 offsetParent 元素的頂部內邊距的距離。

參考資料

More articles from Iris Blog

Day12: Key Sequence Detection

按下密碼後,在頁面顯示一些驚喜的圖片。

July 5th, 2021 · 1 min read

Day11: Custom Video Player

客製化player播放器,功能包含播放、暫停、音量、速度、快進、快退、全螢幕。

July 3rd, 2021 · 1 min read
© 2020–2021 Iris Blog
Link to $mailto:qweichew@gmail.comLink to $https://github.com/iris1114Link to $https://www.instagram.com/iris.justdoit/Link to $https://www.linkedin.com/in/iris-chew