Getting element position in IE versus other browsers
We all know IE6 is difficult. But there seems to be disparate behavior in positioning in later versions of IE as well, when compared with Firefox or other browsers. I have a simple pair of javascript functions which finds the position of an element, and then displays another element in relation to the first element. The idea is to get the second element, which is somewhat larger, to appear in front of the开发者_运维知识库 first element when the mouse hovers over it. It works fine, except on all versions of Internet Explorer, the position of the second element appears different than in Firefox.
The code to get the position of an element is:
function getPosition(e)
{
var left = 0;
var top = 0;
while (e.offsetParent) {
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
}
And the actual rollover display code is:
var pos = getPosition(elem1);
elem2.style.top = pos.y - 8;
elem2.style.left = pos.x - 6;
In Firefox, elem2
appears directly over elem1
, as I want it to. But in IE7 or IE8 it appears way off. What is the reason this occurs, and is there a way to fix it?
elem2.style.top = pos.y - 8;
CSS requires a unit. +'px'
.
(There could conceivably be differences between IE and other browsers depending on how exactly elem2
is positioned.)
As Pointy commented the best thing is to go and look up the jQuery (or YUI that is probably more readable) code. There are normalization needed mainly by the IE quirksmode (but it's not the only issue). For instance (but I'm not sure) I think you need to add to the left/top total amount borders' size of each positioned absolute/relative elements you encounter in the while loop, but in IE6 you need to add borders only if position is absolute at least in quirksmode.
Your code might work without adding more normalization only if you use the DOCTYPE (either Transitional or Strict) as very 1st line of your HTML pages and you reset body/html border/margins and padding. In other words use this line at the beginning of your pages:
<!DOCTYPE...
and in your CSS:
html, body {margin: 0; padding: 0; border-width: 0;}
These anyway might not suffice.
精彩评论