为什么getBoundingClientRect在IE和Firefox中提供不同的值

时间:2012-04-19 14:50:10

标签: javascript html

我有一个Image控件,我需要在图像控件的顶部放置一些元素。当我使用getBoundingClientRect()它在IE(7,8和9)中工作但它在Firefox和Chrome中给出了不同的值。是否还有其他函数可用于获取元素的Bounding矩形?

3 个答案:

答案 0 :(得分:11)

来自getBoundingClientRect的旧IE文档的引用:“在Microsoft®InternetExplorer 5中,窗口的左上角相对于真实客户端是2,2(像素)。”这似乎仍然有效。

在IE9中,使用<meta http-equiv="x-ua-compatible" content="ie=edge"/>“将左上角设置为右侧位置(0,0)。

当d4rkpr1nc3回答时,您可以通过其他方法获取这些值,但结果也取决于所使用的浏览器。我认为你需要一个稍微不同的方法解决这个问题。检查下面的代码,它可能会给你一些想法。

<DIV id="imagecontrol" style="position:absolute;width:200px;height:200px;">
  <DIV id="topleft" style="position:absolute;width:100px;height:100px;left:0px;top:0px;"></DIV>
  <DIV id="topright" style="position:absolute;width:100px;height:100px;right:0px;top:0px;"></DIV>
  <DIV id="bottomleft" style="position:absolute;width:100px;height:100px;left:0px;bottom:0px;"></DIV>
  <DIV id="bottomright" style="position:absolute;width:100px;height:100px;right:0px;bottom:0px;"></DIV>
</DIV>

答案 1 :(得分:5)

不同浏览器的值可能略有不同,但getBoundingClientRect()仍然是性能和准确性的最佳选择。它返回的坐标是相对于视口而不是文档,但是,您需要使用窗口/文档上的滚动值来解释它。

这是关于此的好文章:

http://weblogs.asp.net/bleroy/archive/2008/01/29/getting-absolute-coordinates-from-a-dom-element.aspx

大卫马克很擅长这件事。以下是来自comp.lang.javascript的提示:

https://groups.google.com/forum/?fromgroups#!topic/comp.lang.javascript/zWJaFM5gMIQ

答案 2 :(得分:3)

您可以使用偏移来执行此操作,如下所示:

var top = element.offsetTop;
var left = element.offsetLeft;
var width = element.offsetWidth;
var height = element.offsetHeight;
var bottom = top + height;
var right = left + width;