programing

jquery가 있는 div의 하단 위치 찾기

codeshow 2023. 10. 4. 23:03
반응형

jquery가 있는 div의 하단 위치 찾기

나는 디바가 있는데 맨 아래 위치를 찾고 싶습니다.이렇게 디브의 상단 위치를 찾을 수 있는데 하단 위치를 어떻게 찾나요?

var top = $('#bottom').position().top;
return top;

상단에 외부 높이를 추가하면 상위 요소에 대한 하단이 표시됩니다.

var $el = $('#bottom');  //record the elem so you don't crawl the DOM everytime  
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin

절대적으로 배치된 요소를 사용하거나 문서에 상대적으로 배치할 때는 대신 오프셋을 사용하여 평가해야 합니다.

var bottom = $el.offset().top + $el.outerHeight(true);

trnels에서 지적한 바와 같이 이것은 100% 작동하지 않습니다.위치가 지정된 요소에 이 방법을 사용하려면 오프셋도 고려해야 합니다.예를 들어 다음 코드를 참조합니다.

var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);

편집: 이 솔루션은 이제 원래 답변에도 들어 있습니다.

인정된 답변이 정확하지 않습니다.위치() 함수는 상위 함수에 상대적인 함수이므로 사용해서는 안 됩니다.전역 측위(Global Positioning)를 수행하는 경우(대부분의 경우?)다음과 같이 외부 높이와 함께 오프셋 상단만 추가해야 합니다.

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);

문서 http://api.jquery.com/offset/

var bottom = $('#bottom').position().top + $('#bottom').height();

지금까지의 답은 효과가 있을 것입니다.패딩, 테두리 등 없이 높이만 사용하고자 하는 경우

패딩, 테두리 및 마진을 계산하려면 다음을 사용해야 합니다..outerHeight.

var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);

하단은 여백이나 패딩을 포함하지 않기 때문에 가 아닌 +입니다.

var $bot,
    top,
    bottom;
$bot = $('#bottom');
top = $bot.position().top;
bottom = top + $bot.outerHeight(true); //true is necessary to include the margins
var top = ($('#bottom').position().top) + ($('#bottom').height());

이것은 jquery가 실제로 DOM이 이미 제공하는 것보다 더 복잡하게 만드는 경우 중 하나입니다.

let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;

이 스크립트를 사용하여 div의 끝을 계산합니다.

$('#bottom').offset().top +$('#bottom').height()

언급URL : https://stackoverflow.com/questions/12749844/finding-the-position-of-bottom-of-a-div-with-jquery

반응형