Theme NexT works best with JavaScript enabled

ShunNien's Blog

不積跬步,無以致千里;不積小流,無以成江海。

0%

JS30紀錄 16-Mouse Move Shadow

目標

讓文字陰影因為滑鼠移動而移動。
target

Demo | Github

處理步驟

步驟 1.

  • 因為 .hero 的樣式被設定滿版,所以直接取得 .heroDOM
  • 建立 mousemove 事件與綁定 shadow

步驟 2.

此步驟需要注意的是,利用 offset 來計算,另外因為事件綁定是 mousemove 所以在移動到文字上時,所取得的 offset 值會變成該文字 DOM 內的資料,所以需要進行判斷式,來針對數值調整

  • 設定變數 walk 為陰影移動固定值
  • shadow 內,取得 hero 的長寬,利用 offsetWidthoffsetHeight
  • shadow 內,利用 e 取得目前滑鼠在畫面中的 offsetXoffsetY
  • e.target 為文字 DOM 時,讓數值添加 offsetLeft 或是 offsetTop

步驟 3.

  • 使用 Math.round() 來取整數近似值
  • 為了使陰影移動到文字的上邊與左邊,計算出來的值扣除 walk 的一半
1
2
const xWalk = Math.round(mouseX / width * walk - walk / 2);
const yWalk = Math.round(mouseY / height * walk - walk / 2);
  • 添加多組陰影

筆記與備註事項

HTML 部分

contenteditable

表示該元素是否可以被使用者編輯

JavaScript 部分

Math.round()

Math.round() 函數回傳四捨五入後的近似值.
資料來源 - MDN

MouseEvent.offsetXMouseEvent.offsetY

滑鼠移動點與事件對象在 X 軸或是 Y 軸的偏移量值。

HTMLElement.offsetLeftHTMLElement.offsetTop

offsetLeft 返回當前元素左上角相對於 HTMLElement.offsetParent 節點的左邊界偏移的像素值。

offsetTop 返回當前元素相對於 offsetParent 元素頂部的偏移值。

HTMLElement.offsetWidthHTMLElement.offsetHeight

Dimensions-offset
資料來源 - MDN

參考資料

歡迎關注我的其它發布渠道