iT邦幫忙

2024 iThome 鐵人賽

DAY 28
1
Modern Web

元素不可思議事件簿系列 第 28

Day 28 - 有時候運氣太好不一定是好事

  • 分享至 

  • xImage
  •  

img

圖片來源:Threads
可能會交換靈魂也說不...呀哈。

本篇紀錄不可思議事件:copy事件。

事件其卅一:copy

此事件發生於人類複刻元素之內容之時,通常為鼠輩點按元素某處後拖曳選取元素並釋放,或按壓鍵石ctrlC時得複刻元素之內容。

規範原文:
When the user initiates a copy action, the user agent fires a clipboard event named copy.

複刻之內容可操以文件之術法getSelection()取得,然此術回傳之物為一Selection物件,若要取得內容之文字,可以toString()之術取得。

以下示例將製一簡易今日運勢抽籤器。

const textForCopy = document.querySelector(".text-copy");
const todaysFortune = document.querySelector(".fortune-today");

function drawFortune(event) {
  const selectionText = document.getSelection().toString();
    
  // 機密內容
}

textForCopy.addEventListener("copy", drawFortune);

分段註釋如下:
選取文字元素與今日運勢元素。

const textForCopy = document.querySelector(".text-copy");
const todaysFortune = document.querySelector(".fortune-today");

定義函式之術drawFortune,內容為操以文件之術法getSelection()toString()之術取得選取之文字後,施以機密函式內容以取得今日運勢元素之內容。

function drawFortune(event) {
  const selectionText = document.getSelection().toString();
    
  // 機密內容
  todaysFortune.textContent = "???";
  // 機密內容
}

於文字元素設定copy事件之觀測器,於使用者複刻文字元素之時施以drawFortune函式之術。

textForCopy.addEventListener("copy", drawFortune);

鼠輩選取文字元素後同時按壓鍵石ctrlC,即可顯示本日運勢。
img

何不抽今日之運勢乎?

看來紀錄者今日運勢不佳。

補充紀錄:Selection物件

Selection物件內含名帶anchor之屬性及名帶focus之屬性,前者表使用者選取之起始,後者表使用者選取之終末。

MDN:
The anchor is where the user began the selection and the focus is where the user ends the selection.

下圖為使用者由左至右選取第一字「複」。
img

Selection物件內之anchorOffset屬性值為0,表起始之處為第一字符前方,而focusOffset屬性值為1,表終末之處為第二字符前方。
img

示例之術式

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

翻譯

鼠輩:滑鼠
鍵石:鍵盤按鍵
複刻:複製
文件:document

相關連結


上一篇
Day 27 - 甲賀忍蛙從樹林中歸來
下一篇
Day 29 - 自主性感官子午線反應
系列文
元素不可思議事件簿30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
++
iT邦新手 5 級 ‧ 2024-10-12 00:10:46

https://ithelp.ithome.com.tw/upload/images/20241012/20169139y8cQk4T6VP.png
😍😍😍

橘子 iT邦新手 5 級 ‧ 2024-10-12 00:33:08 檢舉

一定是設計有問題ಥ⁠‿⁠ಥ

我要留言

立即登入留言