Possible jQuery.fn.position improvement
Hi, I'm quite new to jQuery.
I've encountered inconsistent behavior of position(), here is a
simplest repro case:
http://jquery.hildebrand.cz/position-simple.html
http://jquery.hildebrand.cz/position-wrapped.html
Wrapped version is incorrect, I would expect same result as in simple
case, because position of the id1 div didn't change.
There are 2 inconsistencies:
a) different result than in simple case
b) inconsistent behavior in X and Y
I've been digging into sources and found these lines in JQuery 1.2.6
around line 3471 in position() implementation
// Subtract element margins
// note: when an element has margin: auto the
offsetLeft and marginLeft
// are the same in Safari causing offset.left to
incorrectly be 0
offset.top -= num( this, 'marginTop' );
offset.left -= num( this, 'marginLeft' );
This code adapts results to margin settings of source element. So far,
so good.
But what about wrapped case? When margin settings affecting result are
hidden deeper inside DOM hierarchy? That is my case in wrapped
example.
I've tried to replace the code with:
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and
marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
var el = this[0];
var ot = 0;
var ol = 0;
var findFirstSuitableChild = function(el) {
var el = el.firstChild;
while (el && el.nodeType!=1) {
el = el.nextSibling;
}
return el;
};
while (el) {
var not = num([el], 'marginTop');
var nol = num([el], 'marginLeft');
ot = not>ot?not:ot;
ol = nol>ol?nol:ol;
el = findFirstSuitableChild(el); // should return top-left most
child
}
offset.top -= ot;
offset.left -= ol;
This works better in my test cases, but still there is the
inconsistency between X and Y axes.
Any ideas? Does anybody know a robust solution to this problem?
regards,
Antonin