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

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

提交回复
热议问题