Getting offsetTop of element in a table

前端 未结 1 1617
离开以前
离开以前 2021-02-02 03:24

I can\'t seem to figure out how to get the offsetTop of an element within a table. It works fine on elements outside tables, but all of the elements within a table return the sa

1条回答
  •  醉梦人生
    2021-02-02 03:54

    offsetTop returns a value relative to offsetParent; you need to recursively add offsetParent.offsetTop through all of the parents until offsetParent is null. Consider using jQuery's offset() method.

    EDIT: If you don't want to use jQuery, you can write a method like this (untested):

    function offset(elem) {
        if(!elem) elem = this;
    
        var x = elem.offsetLeft;
        var y = elem.offsetTop;
    
        while (elem = elem.offsetParent) {
            x += elem.offsetLeft;
            y += elem.offsetTop;
        }
    
        return { left: x, top: y };
    }
    

    0 讨论(0)
提交回复
热议问题