找到元素相对于文档的位置 [英] finding element's position relative to the document

查看:109
本文介绍了找到元素相对于文档的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定相对于document / body /浏览器窗口的元素位置最简单的方法是什么?现在我正在使用'.offsetLeft / offsetTop',但是这个方法只给出了相对于父元素的位置,所以你需要确定身体元素中有多少父母,以了解身体/浏览器的相对位置窗口/文档位置。这种方法也很麻烦。

What's the easiest way to determine an elements position relative to the document/body/browser window? Right now I'm using ´.offsetLeft/offsetTop´, but this method only gives you the position relative to the parent element, so you need to determine how many parents to the body element, to know the position relaltive to the body/browser window/document position. This method is also to cumbersome.

推荐答案

您可以遍历 offsetParent DOM。

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

这篇关于找到元素相对于文档的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆