Retrieve the position (X,Y) of an HTML element relative to the browser window

前端 未结 27 3728
闹比i
闹比i 2020-11-21 04:59

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript relative to the browser window.

27条回答
  •  甜味超标
    2020-11-21 05:43

    If you want it done only in javascript, here are some one liners using getBoundingClientRect()

    window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y
    
    window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X
    

    The first line will return offsetTop say Y relative to document. The second line will return offsetLeft say X relative to document.

    getBoundingClientRect() is a javascript function that returns the position of the element relative to viewport of window.

提交回复
热议问题