如何取得任何 HTML 標籤右上角的位置

1. 首先,必須先抓到該 HTML 標籤在畫面中「左上角」的位置。

抓到 HTML 物件的絕對位址方法可以用以下 JavaScript function 取得:

function findPosX(obj)
{
    var curLeft = 0;
    if (obj.offsetParent) {
        do {
            curLeft += obj.offsetLeft;
        } while (obj = obj.offsetParent);
    }
    else if (obj.x) {
        curLeft += obj.x;
    }
    return curLeft;
}

function findPosY(obj)
{
    var curTop = 0;
    if (obj.offsetParent) {
        do {
            curTop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    else if (obj.y) {
        curTop += obj.y;
    }
    return curTop;
}

2. 再用 offsetWidth 屬性取得該元素的寬度即可。以下示意圖顯示 offsetWidth 與 offsetHeight 包含的範圍(內容、內距、邊框與捲軸,不包含外距):

offsetWidth 與 offsetHeight 包含內容、內距、邊框及捲軸,但不包含外距
圖:MDN Web Docs contributors:Determining the dimensions of elements(CC BY-SA 2.5,原圖未修改)。

留言評論