When trying to retrieve the position (relative to non-static parent) of an element, if later in the code the position (css style) is set to开发者_如何学运维 anything other than the default, static, the values returned (before this css property is supposed to have been set) are wrong (the top left of their static parent). Help?
Makes sense:
var top = $(this).position().top;
var left = $(this).position().left;
console.log(left);
console.log(top);
Console
- main.js:660
- main.js:0
- main.js:800
- main.js:0
- main.js:660
- main.js:100
- main.js:800
- main.js:100
- ...
Doesn't make sense?:
var top = $(this).position().top;
var left = $(this).position().left;
console.log(left);
console.log(top);
$(this).css({
'position': 'absolute', // or relative
});
Console
- main.js:660
- main.js:0
- main.js:660
- main.js:0
- main.js:660
- main.js:0
- ...
Whilst crafting a jsfiddle for @sethobrien I realised I was being dumb.
I was looping over the elements normally, starting from the beginning, when setting the position on each element I was taking it out of the static flow, so the rest of the elements would shuffle up to fill the empty space left. This was why they were getting the same positions.
My solution therefore was to simply loop over them in reverse, as per JQuery .each() backwards
精彩评论