如何从当前屏幕位置获取元素的偏移量? [英] How do I get the offset of an element from the current screen position?

查看:189
本文介绍了如何从当前屏幕位置获取元素的偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用纯Javascript重构我的所有jQuery,除了一个非常具体的值之外,我得到了所有工作。我在这个代码的浏览器供应商中获得了不同的值:

I'm trying to refactor out all my jQuery with pure Javascript, I got everything working except a very specific value. I'm getting a different value depending in the browser vendor for this code :

使用jQuery我会使用:

With jQuery I'd use:

var topSelected = figure.offset().top - $(window).scrollTop();

这是我在没有jQuery时使用DOM的(非工作)尝试:

Here is my (non working) attempt using the DOM without jQuery:

 var rect = figure.getBoundingClientRect(),
     topSelected = (rect.top + document.body.scrollTop) - window.pageYOffset;

我使用此代码获得Chrome中topSelected的完全相同的值,但不是FF。浏览器与浏览器的不同之处是 document.body.scrollTop

I'm getting the exact same value for topSelected in Chrome with this code, but not for FF. The value that differs from browser to browser is document.body.scrollTop.

获取的正确方法是什么元素的偏移量与使用DOM API的滚动顶部之间的差异?

What is the correct way to get the difference between the offset of an element and the scroll top using the DOM API?

我需要支持IE9 +,Firefox和Chrome。

I need to support IE9+, Firefox and Chrome.

推荐答案

我找到了一个解决方案:

I have found a solution for this :

var rect = figure.getBoundingClientRect(),
    topSelected = (rect.top + (document.documentElement.scrollTop || document.body.scrollTo)) - window.pageYOffset;

它的作用是检查的值.document.documentElement.scrollTop 。在Chrome中,这总是返回0.因此,如果返回0,则 document.body 作为元素提供给 scrollTop 函数在括号外。

What it does is to check the value of document.documentElement.scrollTop. In Chrome this always returns 0. So if 0 is returned, document.body is given as element to the scrollTopfunction outside the parenthesis.

TL; DR

要正确获取偏移量:

Firefox - > document.documentElement

Chrome - > document.body

To get the offset correctly:
Firefox --> document.documentElement
Chrome --> document.body

这篇关于如何从当前屏幕位置获取元素的偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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