How to get the pageX and pageY of an Element without using event

后端 未结 5 2043
旧巷少年郎
旧巷少年郎 2021-01-05 02:00

Is there anyway to the positioning of any element without using e.pageX and e.pageY.

Check this fiddle

The fiddle is actually a poor attempt at what im tryi

5条回答
  •  长发绾君心
    2021-01-05 02:21

    If Im understanding right:

    UIEvent.PageX/PageY: relative to the document (https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/pageX)

    Elem.getBoundingClientRect: relative to viewport.(https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect)

    Window.pageXOffset/pageYOffset:number of pixels that the document is currently scrolled. (https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollX)

    Based on the following description:

    const PageX = (elem) => window.pageXOffset + elem.getBoundingClientRect().left
    const PageY = (elem) => window.pageYOffset + elem.getBoundingClientRect().top
    

提交回复
热议问题