Skip to content Skip to sidebar Skip to footer

Why Getboundingclientrect Gives Different Values In Ie And Firefox

I have an Image control and I need to place some elements on top of the image control. when I used getBoundingClientRect() it is working in IE(7,8 and 9) but It is giving different

Solution 1:

Citation from old IE documentation for getBoundingClientRect: "In Microsoft® Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client." This still seems to be valid.

In IE9 usage of <meta http-equiv="x-ua-compatible" content="ie=edge"/> "sets" the upper-left corner to it's right position (0,0).

As d4rkpr1nc3 answered, you can get those values by other methods, but the results depend on the used browser too. I think you'll need a slightly different approach to this problem. Check the code below, it might give you some ideas.

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

Solution 2:

The values maybe slightly different in different browsers but getBoundingClientRect() is still your best bet for performance and accuracy. The coordinates it returns are relative to the viewport rather than the document, however, so you'll need to account for that using scroll values on the window / document.

Here's a good blog post about this:

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

David Mark is good on this stuff. Here's a tip of his from comp.lang.javascript:

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

Solution 3:

You could use offsets to do that, like this:

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

Post a Comment for "Why Getboundingclientrect Gives Different Values In Ie And Firefox"