[原]js获取dom元素的实际位置及相对坐标

Posted ┓天空之城┏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[原]js获取dom元素的实际位置及相对坐标相关的知识,希望对你有一定的参考价值。

关键API:

Element.getBoundingClientRect()

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

 

用法:

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);

 

获取相对位置:

var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

alert(‘Element is ‘ + offset + ‘ vertical pixels from <body>‘);

 

参考网址:http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element

 

我只是个搬运工,一起学习了~

以上是关于[原]js获取dom元素的实际位置及相对坐标的主要内容,如果未能解决你的问题,请参考以下文章