[JS30] Day22: Follow Along Links
這一天的目標是要製作當我們滑鼠滑到超連結,會有一個跟著移動的白色背景塊,主要學習getBoudingClientRect()知道一個元素的位置寬高,並透過mouseenter來觸發。
JavaScript
首先,將要觸發的元素,也就是所有的<a>選取,
製作一個<span>為白色背景塊,加入.highlight的 class 並放入document.body
const triggers = document.querySelectorAll("a");
const highlight = document.createElement("span");
highlight.classList.add("highlight");
document.body.append(highlight);
針對於每個 trigger,要得到他們的寬高、在視窗的位置,並指定給白色背景塊來呈現出 highlight 的效果。
function highlightLink() {
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords);
const coords = {
width: linkCoords.width,
height: linkCoords.height,
top: linkCoords.top + window.scrollY, // top 跟 left 是根據viewport,所以要再加上滾動的x, y
left: linkCoords.left + window.scrollX,
};
highlight.style.width = `${coords.width}px`;
highlight.style.height = `${coords.height}px`;
highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}
triggers.forEach((a) => a.addEventListener("mouseenter", highlightLink));
getBoudingClientRect 圖例參考(取自 MDN)
