简体   繁体   中英

How to calculate the distance between the top-left corner of an HTML element and the window top-left corner?

Is there an easily way to do that? Consider having properties like: border, padding. Would that method work even with box-sizing: content-box/border-box?

perhaps I do not understand your question, but

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetLeft (Or same link except offsetLeft, I can't post more then 2 links yet :P)

https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

Let me know if those links don't solve it!

DEMO

Perhaps you may be looking similar to position or offest in jquery can be simply achieved by using jQuery as follows

HTML

<div class="box">Lorem ipsum dores.</div>

jQuery

var $box = $('.box');
alert( $box.offset().top)

Hope this helps!

The function

element.getBoundingClientRect()

solves the problem.

More about it can be found here:

https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM