JS30 Day 16 筆記


Posted by GL on 2023-05-25

功能

做出隨著滑鼠位置的移動,文字相對偏移

Demo

播放

step 1 : 獲取 HTML 元素和偏移值

// 拿到 form 元素
const hero = document.querySelector('.hero')
const text = hero.querySelector('h1')
const walk = 100

step 2 : 監聽 mousemove 事件

// 監聽 mousemove 事件,mousemove 時觸發 shadow function
 hero.addEventListener('mousemove', shadow)

step 3 : 建立 shadow function

offsetLeft:element 到 offsetParent 的左距
offsetTop:element 到 offsetParent 的上距
offsetWidth: element 的寬
offsetHeight: element 的高
offsetXoffsetY: element 到外層容器的距離

function shadow(e) {
  // ES6 的解構賦值
  // const width = hero.offsetWidth
  // const height = hero.offsetHeight
  // let x = e.offsetX
  // let y = e.offsetY
  const { offsetWidth: width, offsetHeight: height } = hero
  // 滑鼠的座標
  let { offsetX: x, offsetY: y } = e


  // this: addEventListener 監聽的對象(hero)
  // e.target: 隨著觸發事件而不同,有可能不是 .hero 而是 h1 元素
  if (this !== e.target) {
    x = x + e.target.offsetLeft 
    y = y + e.target.offsetTop
  }

  // (x / width) 可以取得當前滑鼠 X 在 width 的百分比,此時原點在畫面左上角
  // ((x / width) * walk) - (walk / 2 ) 原點移至畫面中心
  // Math.round:將數值四捨五入
  const xWalk = Math.round((x / width * walk) - (walk / 2))
  const yWalk = Math.round((y / height * walk) - (walk / 2))

  // 把 xWalk 和 yWalk 的值代入 text 的 textShadow style 中
  // text-shadow : offset-x | offset-y | blur-radius | color
  text.style.textShadow = `
    ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
    ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
    ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
    ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
  `
}

參考資料:


#JS 30







Related Posts

Kotlin 學習社群 - Kotlin Tips

Kotlin 學習社群 - Kotlin Tips

 JQ總務處|自訂特效函式|深入淺出jQuery

JQ總務處|自訂特效函式|深入淺出jQuery

Leetcode 刷題 pattern - Fast & Slow Pointer

Leetcode 刷題 pattern - Fast & Slow Pointer


Comments