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

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

问题描述

确定元素相对于文档/正文/浏览器窗口的位置的最简单方法是什么?

What's the easiest way to determine an elements position relative to the document/body/browser window?

现在我使用的是.offsetLeft/offsetTop,但是这个方法只给你相对于父元素的位置,所以你需要确定body元素有多少个父元素,才能知道相对于正文/浏览器窗口/文档位置的位置.

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.

这个方法也很麻烦.

推荐答案

您可以遍历 offsetParent 到 DOM 的顶层.

You can traverse the offsetParent up to the top level of the DOM.

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

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

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