有没有一种简单明了的jQuery方法来查找元素的相对位置?换句话说:查找第一个具有css属性position: relative或body-element的父元素(如果没有父元素具有position: relative)。
我不知道父类的css-class或其他什么。
发布于 2010-03-11 18:59:01
从加载到$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"发布于 2014-03-28 19:48:33
我假设你想知道这一点,以便从它的第一个相对父元素计算子元素的位置。我建议更好的方法是只使用jQuery的.offsetParent()计算,它也会寻找位置fixed和absolute的父级,因为它们对孩子的位置有类似的影响。
也就是说,这里有一个关于如何使用.offsetParent()来计算它的相对位置(see 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
});https://stackoverflow.com/questions/2424306
复制相似问题