iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 23
0
Modern Web

寫JS30天系列 第 23

JS 30 - 23 - Follow Along Link Highlighter

今天要學習的是:取得元素在畫面位置的相關資訊

首先我們希望當滑鼠移動到連結上時,可以有highlight效果
此highlight效果會從上一個位置移動到當前滑到的連結上

const triggers = document.querySelectorAll('a');
const highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.append(highlight);
function highlightLink() {
    //do something here!
}

triggers.forEach(a => a.addEventListener('mouseenter', highlightLink))

我們使用querySelectorAll()選取所有要做效果的<a>
然後根據CSS的class,創建一個.highlight<span>
並把他掛在body之下
接著我們需要監聽所有的'mouseenter'事件

當滑鼠移到<a>
要將highlight也移動到<a>
我們可以使用.getBoundingClientRect()取得當前監聽著的<a>的座標位置與長寬
接著只要將長寬和座標軸給highlight的CSS即可
詳細程式碼如下:


function highlightLink() {
    const linkCoords = this.getBoundingClientRect();
    highlight.style.width = `${linkCoords.width}px`;
    highlight.style.height = `${linkCoords.height}px`;
    highlight.style.transform = `translate(${linkCoords.left}px, ${linkCoords.top}px)`;
}

這時候再測試就會發現成功了!

但是
如果當你把網頁往下滑動的時候
會發現highlight沒辦法正確的顯示在<a>
這是因為給highlight的top和left是相對於父層元素(body)的距離

position: absolute;的緣故

所以我們要做小修正

function highlightLink() {
    const linkCoords = this.getBoundingClientRect();
    const coords = {
        width: linkCoords.width,
        height: linkCoords.height,
        left: linkCoords.left + window.scrollX,
        top: linkCoords.top + window.scrollY,
    }
    highlight.style.width = `${coords.width}px`;
    highlight.style.height = `${coords.height}px`;
    highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}

Demo
完整程式碼


上一篇
JS30 - 22 - Geolocation
下一篇
JS30 - 24 - Speech Synthesis
系列文
寫JS30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言