2012-02-25 17 views
5

क्यों 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

ठीक है, डीओएम तत्वों में 'शैली' विशेषताएं नहीं हैं। तो आप उनकी 'शैली' विशेषताओं को नहीं प्राप्त कर सकते हैं। –

+0

'elem.style' शैली * संपत्ति * तक पहुंच रहा है जो तत्वों के पास है। – pimvdb

उत्तर

22

.style संपत्ति शैलियों को प्राप्त करने के लिए है जो सीधे तत्व पर रखी गई थीं। यह आपकी स्टाइलशीट से शैलियों की गणना नहीं करता है।

getComputedStyle() देखें।

+0

: मैं अपना कोड (सीएसएस फ़ंक्शन) अपडेट करता हूं, अब यह अच्छी तरह से काम कर सकता है – artwl

1

तत्वों एक सीएसएस ऊंचाई या चौड़ाई निर्दिष्ट नहीं है।

ध्यान दें कि आप "अनुरोध किए गए" आकार प्राप्त करने की कोशिश कर रहे हैं, वास्तविक आकार नहीं। इसलिए आउटपुट सही है।

यदि आप प्रभावी आकार प्राप्त करना चाहते हैं, तो jQuery width() और height() विधियों का उपयोग करें। http://api.jquery.com/width/

संबंधित मुद्दे