今日任務: 滑鼠移到超連結附近就highligt
創一個span元素加上css,再放進body裡面(此時還看不到因為還沒給寬高)
const triggers = document.querySelectorAll('a');
const spotlight = document.createElement('span');
spotlight.classList.add('highlight');
document.body.append(spotlight);
常用事件介紹(更多滑鼠事件詳細):
triggers.forEach((trigger) => {
trigger.addEventListener('mouseenter', hightlightLink);
});
function hightlightLink(){
console.log(this);
}
Element.getBoundingClientRect()
: 取得元素包含border的寬高和「相對於視窗」的座標
function hightlightLink(){
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords);
}
function hightlightLink(){
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords.width);
spotlight.style.width=`${linkCoords.width}px`;
spotlight.style.height=`${linkCoords.height}px`;
}
transform: translate(X, Y)
: 左右平移X的距離,上下平移Y的距離
function hightlightLink(){
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords.width);
spotlight.style.width=`${linkCoords.width}px`;
spotlight.style.height=`${linkCoords.height}px`;
spotlight.style.transform =`translate(${linkCoords.x}px,${linkCoords.y}px)`;
}
window.scrollY
在D13有學到過:
從頂部開始捲軸已捲動的長度,別名window.pageYOffset
function hightlightLink() {
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords);
const coords = {
width: linkCoords.width,
height: linkCoords.height,
x: linkCoords.x + window.scrollX,
y: linkCoords.y + window.scrollY,
};
spotlight.style.width = `${coords.width}px`;
spotlight.style.height = `${coords.height}px`;
spotlight.style.transform = `translate(${coords.x}px,${coords.y}px)`;
}
今日學習到的:
mousemove event
: 滑鼠移動時觸發,通常在需要用到時才綁定,避免不斷觸發。mouseenter event
: 滑鼠進入元素邊界時觸發,事件不會 bubble。mouseleave event
: 滑鼠完全離開元素時觸發,事件不會 bubble。mouseover event
: 滑鼠經過元素或其子元素之一上時觸發,事件會 bubble。mouseout event
: 滑鼠離開元素時觸發,事件會 bubble。Element.getBoundingClientRect()
: 取得元素包含 border的寬高和「相對於視窗」的座標transform: translate(X, Y)
: 左右平移X的距離,上下平移Y的距離效果連結:連結
參考連結:
MDN: mouseenter event
MDN: getBoundingClientRect()
Mouse Event 小筆記
getBoundingClientRect 的用法