在 JavaScript 中獲取元素相對於其父元素的偏移位置
要獲取 HTML 元素相對於其父元素的偏移位置,可以使用 offsetLeft
和 offsetTop
元素的屬性。
下面是例子:
const div = document.querySelector('.pizza');
console.log(`Offset Position: (${div.offsetTop}, ${div.offsetLeft})`);
上面的示例打印元素相對於其父像素的左上角坐標。默認情況下,元素的左上角是 (0, 0)
. scrollLeft
和 scrollTop
屬性是相對於默認坐標的。