这是我为我们正在进行的项目制作的 jQuery 扩展。我想这可能是你正在寻找的。
$.fn.relativePositionToAncestor = function (ancestor) {
var positionedAncestor = $(ancestor);
var object = $(this);
var relativeOffset = { left: 0, top: 0 };
var leftSpacing = parseInt(object.css("margin-left"));
var topSpacing = parseInt(object.css("margin-top"));
relativeOffset.left -= leftSpacing;
relativeOffset.top -= topSpacing;
var offsetParent = object.offsetParent();
while (offsetParent[0] !== positionedAncestor[0] && !offsetParent.is('html')) {
var offsetParentPosition = offsetParent.position();
var offsetParentPositionLeft = offsetParentPosition.left;
var offsetParentPositionTop = offsetParentPosition.top;
relativeOffset.top -= offsetParentPositionTop;
relativeOffset.left -= offsetParentPositionLeft;
leftSpacing = parseInt(offsetParent.css("margin-left"));
leftSpacing += parseInt(offsetParent.css("border-left-width"));
topSpacing = parseInt(offsetParent.css("margin-top"));
topSpacing += parseInt(offsetParent.css("border-top-width"));
relativeOffset.left -= leftSpacing;
relativeOffset.top -= topSpacing;
offsetParent = offsetParent.offsetParent();
}
return relativeOffset;
};