[原]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

 

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

posted @ 2017-04-26 11:22  sky0014  阅读(2576)  评论(0编辑  收藏  举报