문제

요소의 렌더링 높이를 어떻게 얻습니까?

당신이 있다고 가정 해 봅시다 <div> 내부에 일부 콘텐츠가있는 요소. 내부 의이 내용은 <div>. 높이를 명시 적으로 설정하지 않았을 때 "렌더링 된"높이를 어떻게 얻습니까? 분명히, 나는 시도했다 :

var h = document.getElementById('someDiv').style.height;

이 작업을 수행하는 트릭이 있습니까? 도움이된다면 jQuery를 사용하고 있습니다.

도움이 되었습니까?

해결책

그냥 있어야합니다

$('#someDiv').height();

jQuery와 함께. 이것은 랩핑 된 세트에서 첫 번째 항목의 높이를 숫자로 검색합니다.

사용하려고합니다

.style.height

처음에 속성을 설정 한 경우에만 작동합니다. 별로 유용하지 않습니다!

다른 팁

하나를 시도하십시오 :

var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;

clientHeight 높이와 수직 패딩이 포함됩니다.

offsetHeight 높이, 수직 패딩 및 수직 경계가 포함됩니다.

scrollHeight 포함 된 문서의 높이 (스크롤의 경우 높이보다 높음), 수직 패딩 및 수직 경계가 포함됩니다.

비 jQuery 사용하는 링크가 많이 있었기 때문에 elem.style.height 이 답변의 맨 위에 ...

내부 높이 :
https://developer.mozilla.org/en-us/docs/web/api/element.clientheight

document.getElementById(id_attribute_value).clientHeight;

외부 높이 :
https://developer.mozilla.org/en-us/docs/web/api/htmlelement.offsetheight

document.getElementById(id_attribute_value).offsetHeight; 

또는 내가 가장 좋아하는 참조 중 하나 : http://youmightnotneedjquery.com/

당신이 사용할 수있는 .outerHeight() 이 목적을 위해.

그것은 당신에게 요소의 전체 렌더링 높이를 줄 것입니다. 또한 설정할 필요가 없습니다 css-height 요소의. 예방 조치를 위해 높이를 유지할 수 있습니다 자동 따라서 컨텐츠의 높이에 따라 렌더링 할 수 있습니다.

//if you need height of div excluding margin/padding/border
$('#someDiv').height();

//if you need height of div with padding but without border + margin
$('#someDiv').innerHeight();

// if you need height of div including padding and border
$('#someDiv').outerHeight();

//and at last for including border + margin + padding, can use
$('#someDiv').outerHeight(true);

이러한 기능을 명확하게보기 위해 jQuery 사이트 또는 여기에 자세한 게시물.

그것은 그것을 지울 것입니다 차이점 ~ 사이 .height() / innerHeight() / outerHeight()

style = window.getComputedStyle(your_element);

그런 다음 간단히 : style.height

나는 이것을 사용한다 :

document.getElementById('someDiv').getBoundingClientRect().height

또한 사용할 때도 작동합니다 가상 돔. 나는 다음과 같이 vue에서 그것을 사용합니다.

this.$refs['some-ref'].getBoundingClientRect().height

확실히 사용하십시오

$('#someDiv').height()   // to read it

또는

$('#someDiv').height(newHeight)  // to set it

방금 배운 몇 가지 중요한 것들이 있기 때문에 이것을 추가 답변으로 게시하고 있습니다.

나는 거의 오프 스테 오이트를 사용하는 함정에 빠졌다. 이것이 일어난 일입니다.

  • 나는 디버거를 사용하여 내 요소가 어떤 속성을 가지고 있는지 '시청'하는 좋은 오래된 트릭을 사용했습니다.
  • 나는 내가 기대했던 가치에 대한 가치를 가진 것을 보았다.
  • 그것은 자손이었습니다 - 그래서 나는 그것을 사용했습니다.
  • 그런 다음 숨겨진 div에서 작동하지 않았다는 것을 깨달았습니다.
  • 나는 Maxheight를 계산 한 후 숨어를 시도했지만 서투른 것처럼 보였습니다. 혼란에 빠졌습니다.
  • 검색을했습니다 - 발견 jQuery.height () - 사용했습니다.
  • Height ()가 숨겨진 요소에서도 작동합니다.
  • 재미를 위해 jQuery 구현 높이/폭을 확인했습니다.

다음은 그 중 일부입니다.

Math.max(
Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
Math.max(document.body["offset" + name], document.documentElement["offset" + name])
) 

예, 스크롤과 오프셋을 모두 봅니다. 그것이 실패하면 더 나아 보이면 브라우저 및 CSS 호환성 문제를 고려합니다. 다시 말해서, 나는 신경 쓰지 않는 것입니다.

그러나 나는 할 필요가 없습니다. 감사합니다 jQuery!

이야기의 도덕 : jQuery가 아마도 그럴만 한 이유가있는 방법이 있다면, 아마도 합성과 관련이있을 수 있습니다.

당신이 읽지 않았다면 jQuery 메소드 목록 최근에 나는 당신이 살펴 보는 것이 좋습니다.

나는 jQuery조차 필요하지 않은 간단한 코드를 만들었고 아마도 사람들을 도울 것입니다. 로드 후 'ID1'의 총 높이를 가져 와서 'ID2'에서 사용합니다.

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

그런 다음 몸을로드하도록 설정하십시오

<body onload='anyName()'>

HM 우리는 요소 형상을 얻을 수 있습니다 ...

var geometry;
geometry={};
var element=document.getElementById(#ibims);
var rect = element.getBoundingClientRect();
this.geometry.top=rect.top;
this.geometry.right=rect.right;
this.geometry.bottom=rect.bottom;
this.geometry.left=rect.left;
this.geometry.height=this.geometry.bottom-this.geometry.top;
this.geometry.width=this.geometry.right-this.geometry.left;
console.log(this.geometry);

이 평범한 JS는 어떻습니까?

그래서 이것이 대답입니까?

"무언가를 계산해야하지만 표시하지 않으면 요소를 다음으로 설정하십시오. visibility:hidden 그리고 position:absolute, Dom 트리에 추가하고, 오프 테일을 가져 와서 제거하십시오. (이것이 프로토 타입 라이브러리가 지난번에 확인했을 때 라인 뒤에서하는 일입니다). "

여러 요소에 대해서도 같은 문제가 있습니다. 사이트에는 jQuery 나 프로토 타입이 사용되지 않지만 기술이 작동하면 기술을 빌려주는 데 찬성합니다. 작동하지 못한 것들의 예로서 다음과 같은 코드가 있습니다.

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

기본적으로 기본적으로 모든 것을 시도합니다. 영향을 미치지 않는 클라이언트를 확인하십시오. 문제 요소를 사용하면 일반적으로 기본에서 NAN을, 오프셋 및 스크롤 높이에서 0을 얻습니다. 그런 다음 DOM Solution 및 ClientRect를 추가하여 여기에서 작동하는지 확인했습니다.

2011 년 6 월 29 일, 나는 실제로 코드를 업데이트하여 DOM과 ClientHeight를 예상했던 것보다 더 나은 결과로 추가 시도를 시도했습니다.

1) ClientHeight도 0이었습니다.

2) Dom은 실제로 나에게 큰 높이를 주었다.

3) ClientRects는 DOM 기술과 거의 동일한 결과를 반환합니다.

추가 된 요소는 본질적으로 유동적이기 때문에 비어있는 DOM 온도 요소에 추가되면 해당 컨테이너의 너비에 따라 렌더링됩니다. 이것은 결국 끝나는 것보다 30px 짧기 때문에 이상해집니다.

높이가 어떻게 다르게 계산되는지 설명하기 위해 몇 가지 스냅 샷을 추가했습니다.Menu block rendered normally Menu block added to DOM Temp element

높이 차이는 분명합니다. 나는 확실히 절대적인 포지셔닝과 숨겨질 수는 있지만 그것이 효과가 없을 것이라고 확신합니다. 나는 이것이 효과가 없을 것이라고 계속 확신했다!

(나는 더 멀리 다가옵니다) 높이가 실제 렌더링 된 높이보다 낮아집니다 (렌더링). 이것은 기존 부모와 일치하도록 DOM 온도 요소의 너비를 설정하여 해결할 수 있으며 이론적으로 상당히 정확하게 수행 할 수 있습니다. 또한 제거하고 기존 위치에 다시 추가하여 어떤 결과가 발생할 것인지 모르겠습니다. 그들이 내부 기술을 통해 도착했을 때 나는이 다른 접근법을 사용하여 보게 될 것입니다.

* 하지만 * 그 중 어느 것도 필요하지 않았습니다. 실제로 그것은 광고대로 작동하고 올바른 높이를 반환했습니다 !!!

메뉴를 다시 볼 수 있었을 때 놀랍게도 Dom은 페이지 상단 (279px)의 유체 레이아웃 당 올바른 높이를 반환했습니다. 위의 코드는 또한 280px를 반환하는 getClientRect를 사용합니다.

이것은 다음 스냅 샷에 설명되어 있습니다 (일단 작업 한 후 Chrome에서 가져온).
enter image description here

이제 나는 왜 그 프로토 타입 트릭이 작동하는지에 대한 Noooooo 아이디어를 가지고 있지만 그럴 것 같습니다. 또는 GetClientRects도 작동합니다.

이 특정 요소에 대한이 모든 문제의 원인은 AppendChild 대신 InnerHTML의 사용이라고 생각하지만,이 시점에서 순수한 추측입니다.

offsetHeight, 대개.

무언가를 계산해야하지만 표시하지 않으면 요소를 다음으로 설정하십시오. visibility:hidden 그리고 position:absolute, Dom Tree에 추가하고 offsetHeight, 그것을 제거하십시오. (이것이 프로토 타입 라이브러리가 지난번에 내가 확인했을 때 무대 뒤에서하는 일입니다).

때때로 당신이 만든 요소가 아직 DOM에서 렌더링되지 않았기 때문에 오프 테일이 0을 반환합니다. 나는 그러한 상황에 대해이 기능을 썼습니다.

function getHeight(element)
{
    var e = element.cloneNode(true);
    e.style.visibility = "hidden";
    document.body.appendChild(e);
    var height = e.offsetHeight + 0;
    document.body.removeChild(e);
    e.style.visibility = "visible";
    return height;
}

이미 jQuery를 사용하고 있다면 최선의 방법은 .outerHeight() 또는 .height(), 언급 된 바와 같이.

jQuery가 없으면 사용중인 박스 크기를 확인하고 다양한 패딩 + 국경 + 클라이언트를 추가 할 수 있습니다. 또는 당신이 사용할 수있는 GetComputedStyle:

var h = getComputedStyle (document.getElementById ( 'somediv')). 높이;

h 이제 "53.825px"와 같은 문자열이됩니다.

그리고 나는 참조를 찾을 수 없지만 들었던 것 같아요 getComputedStyle() 비쌀 수 있으므로 아마도 각각에 전화하고 싶은 것이 아닐 것입니다. window.onscroll 이벤트 (그러나 jQuery도 아닙니다 height()).

document.querySelector('.project_list_div').offsetHeight;

mootools와 함께 :

$ ( 'somediv'). getsize (). y

귀하의 질문을 올바르게 이해하면 이와 같은 것이 도움이 될 것입니다.

function testDistance(node1, node2) {
    /* get top position of node 1 */
    let n1Pos = node1.offsetTop;
    /* get height of node 1 */
    let n1Height = node1.clientHeight;
    /* get top position of node 2 */
    let n2Pos = node2.offsetTop;
    /* get height of node 2 */
    let n2Height = node2.clientHeight;

    /* add height of both nodes */
    let heightTogether = n1Height + n2Height;
    /* calculate distance from top of node 1 to bottom of node 2 */
    let actualDistance = (n2Pos + n2Height) - n1Pos;

    /* if the distance between top of node 1 and bottom of node 2
       is bigger than their heights combined, than there is something between them */
    if (actualDistance > heightTogether) {
        /* do something here if they are not together */
        console.log('they are not together');
    } else {
        /* do something here if they are together */
        console.log('together');
    } 
}

CSS의 높이를 구체적으로 설정 했습니까? 당신이 사용할 필요가 없다면 offsetHeight; 보다는 height

var h = document.getElementById('someDiv').style.offsetHeight;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top