标题听起来很厉害(?),不过今天只需要认识一个 Web API - Element.getBoundingClientRect()
~
此元素方法会回传一个DOMRect
物件,物件中会包含选取元素的尺寸和坐标资讯,除了元素的高度和宽度以外,其他的属性都会依据元素当下相对 viewport 的左上角计算距离
换句话说,当上下滚动页面时,y / top
的距离会变动,左右滚动页面时,x / left
的距离会变动
可以用codepen连结观察看看
在有滚动页面的情况下,要取得特定元素相对於文件(Document)左上角的位置时就需要加上滚动的距离,计算公式如下:
元素相对於文件的水平距离: x / left + window.scollX
元素相对於文件的垂直距离: y / top + window.scrollY
图片来源:MDN
width
: 选取元素的宽度height
: 选取元素的高度x / left
: 元素左上角相对视窗的水平距离right
: 元素右下角相对视窗的距离y / top
: 元素左上角相对视窗的垂直距离<span>
并加入到页面中const spotlight = document.createElement('span');
document.body.append(spotlight);
spotlight.classList.add('spotlight');
function highlightLink() {
const linkInfo = this.getBoundingClientRect();
// 位置校正
const coordinate = {
width: linkInfo.width,
height: linkInfo.height,
left: linkInfo.left + scrollX,
top: linkInfo.top + scrollY,
}
spotlight.style.width = `${coordinate.width}px`;
spotlight.style.height = `${coordinate.height}px`;
spotlight.style.transform = `translate(${coordinate.left}px, ${coordinate.top}px)`;
}
const links = document.querySelectorAll('a');
links.forEach(link => {
link.addEventListener('mouseenter', highlightLink);
})
参考资料:
以下笔记摘录自『 The Go Workshop 』。 溢位和越界绕回 如果尝试在建立变数时,赋予一...
我们昨天介绍了 Transformer 的结构,但是并没有介绍到 Transformer 内最神秘的...
在VSCode操作Github提取 *於左方点选 【原始档控制】,点选【•••】 ,点选【提取、推送...
自从国高中我的房间出现了电脑,虽然是很废的文书机,但它还是在夜深人静的凌晨抚慰我睡不着的心情。方形的...
如同前面所说,资料模型需要运用到实际环境中才会发挥价值 Initiation 延续之前辅助决策的初始...