2010-06-16 1 views
5

이 수수께끼에 대한 통찰력을 제공하십시오.document.getElementById()를 사용하여 CSS에서 값 가져 오기 style.height javascript

나는 속성이 div 태그에 포함되어있는 경우 내가 잘이 값을 얻을 수 있습니다

var high = document.getElementById("hintdiv").style.height; 
alert(high); 

에 의해 사업부 상자에서 높이 값을 얻기 위해 노력하고 있지만,이 속성이 경우 빈 값을 반환 css 섹션에 정의되어 있습니다.

괜찮습니까? 100px 값으로 표시됩니다. 값에 액세스 할 수 있습니다.

<div id="hintdiv" style="height:100px; display: none;"> 
. 
. 
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

이 메시지는 비어있는 경고 화면을 보여줍니다. 값은 거의 0

#hintdiv 
{ 
height:100px 
display: none; 
} 

<div id="hintdiv"> 
. 
. 
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

이다 그러나 나는 아무 문제/접근하지 않는 "디스플레이 : 없음"변경해야 함 태그 또는 CSS 섹션에 있는지 여부 속성을. 태그 또는 css 섹션에서 두 속성 정의 메서드에 의해 div 상자가 올바르게 표시됩니다.

나는 다른 변화에 의해 값에 액세스하려고했으나 운

document.getElementById("hintdiv").style.height.value ----> undefined 
document.getElementById("hintdiv").height ---->undefined 
document.getElementById("hintdiv").height.value ----> error, no execution 

모든 솔루션?

TIA.

+4

참조 http://stackoverflow.com/questions/1098349/reading-non-inline-css-style-info-from-javascript 및 http://stackoverflow.com/questions/1048336/cant-access-css- 선택자 - 속성 - 자바 스크립트 –

+0

참고 : http://gist.github.com/369133 및 http://stackoverflow.com/questions/2531737/javascript-incapable-of-getting-elements-max-height-via -element-style-maxheight/ – CMS

+0

감사합니다. 이것은 분명히 예상치 못한 일이었습니다. 나는이 1 (또는 2 요소)에 대한 인라인 스타일을 수행 할 것입니다. – Jamex

답변

-1

대신 usign jQuery를 고려해야합니다 ... $ ('# hintDiv'). height()로 단순화하고 항상 div의 실제 너비를 반환합니다.

+3

너비! == 높이 :) – epascarello

+0

감사합니다 DevIT, jquery 책을 가져와야합니다. – Jamex

+0

안녕 epascarello! 다행스럽게도 도움이 될 수 있지만 ... jQuery를 사용하려면 책이 절대 필요하지 않습니다. jQuery의 웹 사이트 (http://docs.jquery.com/Tutorials)에서 자습서를 사용해보십시오. –

5

document.getElementById("hintdiv").style.height;을 사용하면 태그의 style 속성에 액세스하고 있기 때문입니다. 속성이 없으면 값을 얻지 못합니다.

대신 IE에서는 currentStyle 개체를 사용하고 나머지 웹 브라우저에서는 getComputedStyle() 기능을 사용해야합니다.

1

CSS 구문이 잘못되었습니다. height:100px이 아닌 height:100px; 일 수 있습니다. 세미콜론을 유의하십시오.

관련 문제