Sogrey / Web-QA

https://sogrey.github.io/Web-QA/
MIT License
6 stars 2 forks source link

获取div相对文档的位置 #313

Open Sogrey opened 4 years ago

Sogrey commented 4 years ago

getBoundingClientRect

var offset = document.getElementById("btn").getBoundingClientRect();
//在IE6下有2像素的bug

alert(offset.top);
// alert(offset.left);

offsetLeft + offsetTop

alert(getAbsolutePosition(document.getElementById("btn")).top)
//console.log(offset);

function getAbsolutePosition(obj){
    var left = 0;
    var top = 0;
    while(obj){
        left += obj.offsetLeft;
        top += obj.offsetTop;
        obj = obj.offsetParent;
    }
    return {left:left, top:top};
}

https://blog.csdn.net/se134789836178/article/details/103878137