使用javascript,如何获取元素的位置 [英] Using javascript, how to get the position of an element

查看:87
本文介绍了使用javascript,如何获取元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题所说,如何获取元素在网页中的位置的x,y位置以及它们的定位方案,如绝对,相对等等。

like the title says, how to get the element's x, y positions with respect to their location in the web page and their positioning schemes like absolute, relative etc.

推荐答案

在现代浏览器中,getBoundingClientRect和getClientRects将为您提供描述元素的rect对象。请参阅 https://developer.mozilla.org/en/DOM/element.getBoundingClientRect https://developer.mozilla.org/en/DOM/element.getClientRects

In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects

如果你必须使用IE8,那么你将不得不在不同的浏览器中做不同的事情以获得正确的答案(例如,对象检测getBoundingClientRect并且如果它不存在则回退到其他一些方法)。

If you have to work with IE8, then you'll have to do different things in different browsers to get correct answers (e.g. object-detect getBoundingClientRect and fall back on some other method if it's not present).

jQuery offset()计算和Quirksmode findPos 将在任何进行亚像素定位的浏览器(例如Firefox或IE9)中给出不正确的答案,因为它们会将答案四舍五入为整数个像素。根据您正在做的事情,可能会或可能不会。

The jQuery offset() calculation and the Quirksmode findPos will give incorrect answers in any browser that does subpixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you're doing, that may or may not be ok.

这篇关于使用javascript,如何获取元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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