使用 getBoundingClientRect( ) 函数与 getComputedStyle( ) 函数获取网页元素的坐标
JavaScript 的强大总是待发掘的,它是未来在大多数应用场合不可忽视的语言。
下图展示了一个 DIV 元素,如何获得1、2、3、4各个位置的坐标呢?

首先用 document.querySelector() 获得这个元素。这个元素是个对象,自带了重要的方法 getBoundingClientRect(), 其返回值包含这个元素外框的x、y、right、bottom 四个值。Smart。
x 代表元素外框左上角距离浏览器窗口左侧的距离, y 代表元素外框左上角距离浏览器窗口上侧的距离;right 代表元素外框右下角距离浏览器窗口左侧的距离,bottom 代表元素外框右下角距离浏览器窗口上侧的距离。这样,就可以直接获得点1、2的坐标了。

点3、4 的坐标难计算一点。需要获取边框的厚度信息,可以用 getComputedStyle() 去 CSS 获取。 borderXWidth 是个字符串(比如 "5px"), 需要先将其转为数字。为此,需要先剥离 px, 然后将剩下的字符串用 parseFloat() 函数转为浮点数。

// Suppose you have already got the DIV element, elem.
console.log(elem.getBoundingClientRect().x, elem.getBoundingClientRect().y); // 1
console.log(elem.getBoundingClientRect().right, elem.getBoundingClientRect().bottom); // 2
const style = getComputedStyle(elem); // get CSS values
console.log(elem.getBoundingClientRect().x + parseFloat(stripPx(style.borderLeftWidth)), elem.getBoundingClientRect().y + parseFloat(stripPx(style.borderTopWidth))); // 3
console.log(elem.getBoundingClientRect().right - parseFloat(stripPx(style.borderRightWidth)), elem.getBoundingClientRect().bottom - parseFloat(stripPx(style.borderBottomWidth))); // 4