How to compute getBoundingClientRect() without considering transforms?

后端 未结 3 1190
故里飘歌
故里飘歌 2020-12-15 19:23

getBoundingClientRect() returns the coordinates of an element on the screen after being transformed. How do I calculate those coordinates

3条回答
  •  情歌与酒
    2020-12-15 19:25

    I liked Ghetolay's answer. I used it but I made it a bit more performant by avoiding the loop.

    I have a draggable tag cloud and I have to update the drag position using transforms, but keep track of the original position (without transform).

    The previous answer suggested to loop thru the offsetParents. In my case, and I think in a lot of cases, the tags are transformed but the container isn't. So I only have to get the first offsetParent and use getBoundingClientRect() there. No need to keep looping. I solved it doing this:

    var el = element;
    var parentRect = element.offsetParent.getBoundingClientRect();
    var offsetLeft = parentRect.left + element.offsetLeft;
    var offsetTop = parentRect.top + element.offsetTop;
    

提交回复
热议问题