2012-02-25 4 views
5

this.style[property] 빈 문자열을 받으시겠습니까? 내 코드는 다음과 같습니다javascript this.style [property]가 빈 문자열을 반환하는 이유는 무엇입니까?

<!DOCTYPE html> 
<html> 
<head> 
    <title>Demo</title> 
    <style type="text/css"> 
     #test{ 
      height:100px; 
     } 
     .tclass{ 
      width:100px; 
     } 
    </style> 
    <script type="text/javascript"> 
     function $(ID){ 
      var element=document.getElementById(ID||'nodId'); 
      if(element){ 
       element.css=css; 
      } 
      return element; 
     } 

     function css(prop,value){ 
      if(value==null){ 
       return this.style[prop]; 
      } 
      if(prop){ 
       this.style[prop]=value; 
      } 
      return true; 
     } 

     window.onload=function(){ 
      var element=$("test"); 
      alert(element.css("height")+","+element.css("width")+","+element.css("background")); 

      //alert ,,#ccc 
     }; 
    </script> 
</head> 
<body> 
    <div id="test" style="background:#CCC;" class="tclass">Test</div> 
</body> 
</html> 

이 코드 경고 ,,#ccc,하지만 난 100px,100px,#ccc를 얻을 싶어, 저와 무슨 일이야? 누가 날 도울 수 있죠?

function css(prop,value){ 
     if(value==null){ 
      var b = (window.navigator.userAgent).toLowerCase(); 
      var s; 
      if(/msie|opera/.test(b)){ 
       s = this.currentStyle 
      }else if(/gecko/.test(b)){ 
       s = document.defaultView.getComputedStyle(this,null); 
      } 
      if(s[prop]!=undefined){ 
       return s[prop]; 
      } 
      return this.style[prop]; 
     } 
     if(prop){ 
      this.style[prop]=value; 
     } 
     return true; 
    } 
+0

DOM 요소에는'style' 속성이 없습니다. 그래서 당신은 그들의'style' 속성을 얻을 수 없습니다. –

+0

'elem.style'은 요소에있는 스타일 * 속성 *에 액세스하고 있습니다. – pimvdb

답변

22

.style 속성은 요소에 직접 배치 된 스타일을 가져 오기위한 것입니다. 스타일 시트에서 스타일을 계산하지 않습니다.

getComputedStyle()을 참조하십시오.

+0

: 내 코드 (CSS 기능)를 업데이트하고 이제는 잘 작동 할 수 있습니다. – artwl

1

요소는 지정된 CSS 높이 또는 너비가 없습니다 :

업데이트는 내가 지금은 잘 작동 할 수 있습니다, CSS의 기능을 변경했습니다.

실제 크기가 아닌 "요청 된"크기를 얻으려고합니다. 따라서 출력이 정확합니다. 당신이 효과적인 크기를 얻고 싶다면

는 jQuery를 width()height() 방법을 사용합니다. http://api.jquery.com/width/

관련 문제