iT邦幫忙

2024 iThome 鐵人賽

DAY 19
1

img

圖片來源:大概也是Threads
比瘋子更瘋就是成為瘋子。

本篇紀錄與前篇介紹之focusblur事件相似之不可思議事件:focusinfocusout事件。

事件其十九:focusin

此事件發生於元素受矚之時。focusin事件需發生於元素受矚之後。與focus事件基本上相同,然focusin事件有發泡現象。

規範原文:
A user agent MUST dispatch this event when an event target receives focus. The focus event MUST fire before the dispatch of this event type. This event type is similar to focus, but does bubble.

事件其二十:focusout

focusin事件相反,此事件發生於元素取消受矚之時。focusout事件需於元素取消受矚之後發生。與blur事件基本上相同,然focusout事件有發泡現象。

規範原文:
A user agent MUST dispatch this event when an event target loses focus. The blur event MUST fire before the dispatch of this event type. This event type is similar to blur, but does bubble.

發泡現象有何應用之處?以下示例藉前篇之小桃元素,紀錄一操術法之施行問題。

示例觀測scrollend事件,於鼠輩結束捲動時於下方新生一小桃元素,望此新生之小桃如原先之小桃有相同之邪惡行為。

const momoes = document.querySelectorAll(".momo");
const container = document.querySelector(".container");

function becomeEvil() {
  this.style.backgroundImage = `url("./momo_ya.png")`;
}

function mitte() {
  this.style.backgroundImage = `url("./momo_mitte.png")`;
}

function addMomo() {
  const newMomo = document.createElement("a");
  newMomo.setAttribute("class", "momo");
  newMomo.setAttribute("href", "##");
  container.insertBefore(newMomo, container.lastChild);
}

momoes.forEach((momo) => {
  momo.addEventListener("focus", becomeEvil);
  momo.addEventListener("blur", mitte);

  momo.addEventListener("click", (event) => {
    event.preventDefault();
  });
});

window.addEventListener("scrollend", addMomo);

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

const momoes = document.querySelectorAll(".momo");
const container = document.querySelector(".container");

借用前篇之函式之術becomeEvilmitte,並定義函式addMomo,內容為新增一小桃。

function addMomo() {
  const newMomo = document.createElement("a");
  newMomo.setAttribute("class", "momo");
  newMomo.setAttribute("href", "##");
  container.insertBefore(newMomo, container.lastChild);
}

對於所有小桃元素設定二觀測器,觀測focusblur事件,並於全介面設定事件觀測器以觀測scrollend事件並施以addMomo函式之術。

momoes.forEach((momo) => {
  momo.addEventListener("focus", becomeEvil);
  momo.addEventListener("blur", mitte);
});

window.addEventListener("scrollend", addMomo);

確認原先已存在之小桃可有邪惡行為。
img

然新生之小桃僅可愛,毫無反應。
img

示例處

此因事件觀測器僅設置於原先已存在之小桃,而無法設置於新生之小桃。欲解決此問題,需使用事件委任之特殊術法,將於後篇紀錄之。

示例之術式

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

翻譯

鼠輩:滑鼠
受矚:focus

相關連結


上一篇
Day 18 - 最近朋友推薦我蓮霧麵茶
下一篇
Day 20 - 來談談責任歸屬吧
系列文
元素不可思議事件簿30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
jeremykuo
iT邦新手 5 級 ‧ 2024-10-03 11:06:42

永無止境的小桃著實可怕/images/emoticon/emoticon39.gif

橘子 iT邦新手 5 級 ‧ 2024-10-03 13:47:58 檢舉

這個是真永無止盡,不要輕易嘗試啊( ´゚Д゚`)

我要留言

立即登入留言