简体   繁体   English

如何计算HTML元素的左上角和窗口的左上角之间的距离?

[英]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? 该方法甚至可以与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/zh-CN/docs/Web/API/HTMLElement.offsetLeft (或除offsetLeft以外,其他链接相同,我还不能发布两个以上的链接:P)

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

Let me know if those links don't solve it! 让我知道这些链接是否无法解决问题!

DEMO DEMO

Perhaps you may be looking similar to position or offest in jquery can be simply achieved by using jQuery as follows 也许您看起来与jquery中的职位相似或最差可以通过使用jQuery如下实现

HTML HTML

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

jQuery jQuery的

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

Hope this helps! 希望这可以帮助!

The function 功能

element.getBoundingClientRect() element.getBoundingClientRect()

solves the problem. 解决了问题。

More about it can be found here: 可以在这里找到更多关于它的信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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