iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 16
0
Modern Web

JavaScript 30實作心得筆記系列 第 16

Day16 CSS Text Shadow Mouse Move Effect

Day16 CSS Text Shadow Mouse Move Effect

第16天的實作是做出特定元素的陰影會隨著滑鼠的位置產生位移的變化。

首先在頁面中建立div元素,其中包含文字元素h1

<div class="hero">
    <h1 contenteditable>?Day16 Traing?</h1>
</div>

div的高度被設定為全螢幕,接著在div元素建立mousemove的事件,當滑鼠移過去就觸發該事件。

並取得四個數值 1.為背景寬度,2. 為背景高度 3. 滑鼠在div元素位置中的X值 4. 滑鼠在div位置元素中的Y值。

// 背景寬高度
const Width = heroDiv.offsetWidth
const Heigth = heroDiv.offsetHeigth

// 滑鼠在畫面的位置
let x = e.offsetX
let y = e.offsetY

接下來目標是當滑鼠離文字元素越遠其元素陰影移動會越大,因此需要取得滑鼠在div上的位置。

此時會發現當滑鼠指到divh1是取得滑鼠在h1元素上的位置數值,而滑鼠不是在div的位置數值。

為了知道h1中滑鼠的位置,,要取得h1div的左邊界offsetLeft和上邊界的距離offsetTop,加上當滑鼠指到h1時取得的e.offsetXe.offsetY,這樣即可得知滑鼠在螢幕上的位置,但要加入判斷以避免指到不同元素而造成誤差。

if (this != e.target) {
    x = x + e.target.offsetLeft
    y = y +  e.target.offsetTop
  }

之後將整個畫面轉為百分比的方式,其位置為圖一,左上角的(X,Y)為(0%,0%),右下角的(X,Y)為(100%,100%),但為螢幕中間作為起始點,需要在(X,Y)各減50%,將其轉為圖二。

xWalk = (x / Width * percent) - (percent / 2)
yWalk = (y / Heigth * percent) - (percent / 2)

圖一

圖二

最後將取得數值加入h1中為文字陰影即。

text.style.textShadow = `
    ${xWalk * 1}px ${yWalk * 1}px 0 rgba(255, 0 , 0 , 0.7),
    ${xWalk * -1}px ${yWalk * 1}px 0 rgba(0, 255 , 0 , 0.7),
    ${xWalk * 1}px ${yWalk * -1}px 0 rgba(0, 0 , 255 , 0.7),
    ${xWalk * -1}px ${yWalk * -1}px 0 rgba(255, 255 , 0 , 0.7)
  `

Html:

<div class="hero">
    <h1 contenteditable>?WOAH!</h1>
</div>

Javascript:

  1. MouseEvent()
    The MouseEvent() constructor creates a new MouseEvent.

  2. MouseEvent.offsetX
    指被滑鼠指定的元素上,滑鼠的X軸座標位置。
    The offsetX read-only property of the MouseEvent interface provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

  3. MouseEvent.offsetY
    指被滑鼠指定的元素上,滑鼠的Y軸座標位置。
    The offsetY read-only property of the MouseEvent interface provides the offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node.

  4. HTMLElement.offsetLeft
    指元素離offsetParent的距離,由offsetParent的左邊界至元素左邊界的距離。
    Returns a double, the distance from this element's left border to its offsetParent's left border.

  5. HTMLElement.offsetTop
    指元素離offsetParent的距離,由offsetParent的上邊界至元素上邊界的距離。
    The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.

tags: MouseEvent, HTMLElement

上一篇
Day15 LocalStorage and Event Delegation
下一篇
Day17 Sorting Band Names without articles
系列文
JavaScript 30實作心得筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言