iT邦幫忙

2024 iThome 鐵人賽

DAY 17
1

img

圖片來源:YouTube
就像小垃圾永遠不嫌多。

本篇紀錄與前篇之scroll事件相關之不可思議事件scrollend

事件其十六:scrollend

此事件發生於元素捲動結束之時。元素捲動結束之定義為捲動之位置已無更新,且使用者捲動行為已結束。

另注意,safari無法使用此事件。

以下示例結合觀測scroll事件,針對全介面觀測scrollend事件並施以無盡之鼠之術。

const sevens = document.querySelectorAll(".seven");
const container = document.querySelector(".container");

function showPicture() {
  sevens.forEach((seven) => {
    const currentViewBottom = this.scrollY + this.innerHeight;
    const sevenPosition = seven.offsetTop + seven.offsetHeight / 2;

    if (currentViewBottom > sevenPosition) {
      seven.style.opacity = 1;
    }
  });
}

function addSeven() {
  const newSeven = document.createElement("img");
  newSeven.setAttribute("class", "seven new");
  newSeven.setAttribute("src", "./seven_mochi.png");
  container.insertBefore(newSeven, container.lastChild);
}

window.addEventListener("scroll", showPicture);
window.addEventListener("scrollend", addSeven);

分段註釋如下:
選取所有鼠元素及容器元素。

const sevens = document.querySelectorAll(".seven");
const container = document.querySelector(".container");

定義函式之術,各名為showPictureaddSeven,內容分別為顯示圖片及增加小七鼠。

其中showPicture函式之術法為偵測鼠輩捲動之位置底部
const currentViewBottom = this.scrollY + this.innerHeight;
是否超過小七鼠圖之位置一半處
const sevenPosition = seven.offsetTop + seven.offsetHeight / 2;
若有,則顯示此小七鼠圖
if (currentViewBottom > sevenPosition) { seven.style.opacity = 1; }

function showPicture() {
  sevens.forEach((seven) => {
    const currentViewBottom = this.scrollY + this.innerHeight;
    const sevenPosition = seven.offsetTop + seven.offsetHeight / 2;

    if (currentViewBottom > sevenPosition) {
      seven.style.opacity = 1;
    }
  });
}

function addSeven() {
  const newSeven = document.createElement("img");
  newSeven.setAttribute("class", "seven new");
  newSeven.setAttribute("src", "./seven_mochi.png");
  container.insertBefore(newSeven, container.lastChild);
}

設定二觀測器,對於全介面window觀測scrollscrollend事件,期望當鼠輩捲動時發生scroll事件以顯示小七鼠,鼠輩結束捲動時發生scrollend事件於底部增加一小七鼠。

window.addEventListener("scroll", showPicture);
window.addEventListener("scrollend", addSeven);

首先觀察鼠輩捲動到小七鼠圖之一半位置時,顯示可愛小七鼠圖。
img

示例處

而鼠輩結束捲動行為後,可由右下之捲軸觀得新生之高度,此即為新生之小七鼠。而鼠輩繼續捲動並結束捲動,又可獲得一新生鼠,此為無盡之鼠之術。
img

此真為無盡?若觀者捲之以耐心,則可得意外之喜。鼠巴拉喜。

示例之術式

https://github.com/CReticulata/2024ithome/tree/main/Day17

翻譯

鼠輩:滑鼠
鼠輪:滾輪

相關連結


上一篇
Day 16 - 轉轉轉好運大家一起來
下一篇
Day 18 - 最近朋友推薦我蓮霧麵茶
系列文
元素不可思議事件簿30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
jeremykuo
iT邦新手 5 級 ‧ 2024-10-01 00:19:50

趴在杯子裡看起來很舒服~/images/emoticon/emoticon07.gif

橘子 iT邦新手 5 級 ‧ 2024-10-01 15:22:13 檢舉

為鼠乾杯(・∀・)つ🐹

我要留言

立即登入留言