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

后端 未结 5 2033
旧巷少年郎
旧巷少年郎 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:12

    You may use

    document.getElementById("elementID").offsetTop;
    document.getElementById("elementID").offsetLeft;
    

    Refer to MDN. They return the offset from the parent element. If you need the offset of the element in respect to the whole body it may get more tricky, as you will have to sum the offsets of each element in the chain.
    Respectively for .getElementsByTagName, as each object in the DOM has these attributes.

    .getBoundingClientRect is also worth a look.

    var clientRectangle = document.getElementById("elementID").getBoundingClientRect();
    console.log(clientRectangle.top); //or left, right, bottom
    
    0 讨论(0)
  • 2021-01-05 02:15

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    $("#something").click(function(e){
       var parentOffset = $(this).parent().offset(); 
       //or $(this).offset(); if you really just want the current element's offset
       var relX = e.pageX - parentOffset.left;
       var relY = e.pageY - parentOffset.top;
    });
    </script>

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-05 02:22

    I think offset() should work.

    $(element).offset() //will get {top:.., left:....}
    
    0 讨论(0)
  • 2021-01-05 02:37

    You can find almost all jquery stuff here: http://youmightnotneedjquery.com/

    $(el).offset();
    

    the same as:

    var rect = el.getBoundingClientRect();
    
    {
      top: rect.top + document.body.scrollTop,
      left: rect.left + document.body.scrollLeft
    }
    
    0 讨论(0)
提交回复
热议问题