使用 getBoundingClientRect( ) 函數(shù)與 getComputedStyle( ) 函數(shù)獲取網(wǎng)頁元素的坐標
JavaScript 的強大總是待發(fā)掘的,它是未來在大多數(shù)應(yīng)用場合不可忽視的語言。
下圖展示了一個 DIV 元素,如何獲得1、2、3、4各個位置的坐標呢?

首先用 document.querySelector() 獲得這個元素。這個元素是個對象,自帶了重要的方法 getBoundingClientRect(), 其返回值包含這個元素外框的x、y、right、bottom 四個值。Smart。
x 代表元素外框左上角距離瀏覽器窗口左側(cè)的距離, y 代表元素外框左上角距離瀏覽器窗口上側(cè)的距離;right 代表元素外框右下角距離瀏覽器窗口左側(cè)的距離,bottom 代表元素外框右下角距離瀏覽器窗口上側(cè)的距離。這樣,就可以直接獲得點1、2的坐標了。

點3、4 的坐標難計算一點。需要獲取邊框的厚度信息,可以用 getComputedStyle() 去 CSS 獲取。 borderXWidth 是個字符串(比如 "5px"), 需要先將其轉(zhuǎn)為數(shù)字。為此,需要先剝離 px, 然后將剩下的字符串用 parseFloat() 函數(shù)轉(zhuǎn)為浮點數(shù)。

// 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