요소가 상대 위치에있는 요소를 찾는 간단하고 깨끗한 jQuery 방법이 있습니까? 즉, CSS 속성이 position: relative
인 첫 번째 상위 항목을 찾거나 body 요소 (상위 요소가 position: relative
인 경우)를 찾습니다.jQuery로 상대 요소 찾기
나는 부모의 css-class 또는 whatsover를 알지 못합니다. 요소 시작
요소가 상대 위치에있는 요소를 찾는 간단하고 깨끗한 jQuery 방법이 있습니까? 즉, CSS 속성이 position: relative
인 첫 번째 상위 항목을 찾거나 body 요소 (상위 요소가 position: relative
인 경우)를 찾습니다.jQuery로 상대 요소 찾기
나는 부모의 css-class 또는 whatsover를 알지 못합니다. 요소 시작
난 당신이 먼저 상대의 부모에서 자녀의 위치를 계산하기 위해이 알고 싶어한다고 가정
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"
$elem
에서로드. 더 좋은 접근법은 단지 jQuery의 .offsetParent()
계산을 사용하는 것인데, 이것도 위치 fixed
과 absolute
의 부모를 찾게 될 것입니다. 이것들은 어린이의 위치에 비슷한 영향을 미칠 것입니다.
, 여기가 상대적인 위치 (see JSFiddle)의 계산 .offsetParent()
사용에 대한 당신이 갈 수있는 방법에 빠른 모형을이다 :
// 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
});
절대 위치 자식 요소에 대한 최상의 솔루션! –