是否有一种简单而清晰的jQuery方法来查找元素相对于哪个元素的位置?换句话说:查找第一个具有css属性 position: relative
的父级元素,或者是body元素(如果没有父级元素有 position: relative
属性)。
我不知道父元素的css类或其他信息。
从 $elem
中加载元素开始
var $closestRelativeParent = $elem.parents().filter(function() {
// reduce to only relative position or "body" elements
var $this = $(this);
return $this.is('body') || $this.css('position') == 'relative';
}).slice(0,1); // grab only the "first"
.offsetParent()
计算,它还会查找定位为 fixed
和 absolute
的父级,因为这些也会对子元素的位置产生类似的影响。.offsetParent()
来计算其相对位置 (请参见JSFiddle):// Given a target, find it's first offset parent, and work out the targets position
// relative to the parent, by deducting their respective .offset() values
var $target = $("#bar"),
$offsetParent = $target.offsetParent(),
oTarget = $target.offset(),
oParent = $offsetParent.offset(),
posTop = oTarget.top - oParent.top,
posLeft = oTarget.left - oParent.left;
// Validate this works by cloning #bar and positioning the clone directly on top
// Result should be a blue "bar" rather than a "red" one.
$target.clone().appendTo($offsetParent).attr("id", "confirm").css({
top: posTop,
left: posLeft
});