2014-10-18 39 views
-1

信息我想使用JavaScript 沒有jQuery的或任何其他JS庫從內部/外部styleshet返回風格沒有jQuery的告訴從外部CSS文件或內部樣式表

<style type="text/css"> <!-- From internal/external stylesheet --> 
    div{ 
     height:30px; 
     width:45px; 
     background-color:#4445C7; 
    } 
</style> 
<div id="counter-element" style="width:3px;height:10px;"></div> 
<div id="example"></div> 
<script type="text/javascript"> 
    function getStyle(elem,prop){ 
     return elem.style[prop]; 
    } 
    alert(getStyle(document.getElementById("counter-element"),"origional-background-color"); //I know this won't work. I'm just putting it in for an example 
    alert(getStyle(document.getElementById("example"),"background-color"); 
</script> 
+0

如果你想知道申請什麼風格從直接應用的樣式或樣式表樣式到給定的對象,然後您可以按照[這裏](https://developer.mozilla.org/en-US/docs/Web/API/Window)所述使用'getComputedStyle()'。 getComputedStyle)在MDN中。 – jfriend00 2014-10-18 22:16:42

回答

0

使用這樣var es=getStyle(document.getElementById("someId"),"background-color");

function getStyle(Elm, strCssRule){ 
 
    var strValue = ""; 
 
    if(document.defaultView && document.defaultView.getComputedStyle){ 
 
     strValue = document.defaultView.getComputedStyle(Elm, "").getPropertyValue(strCssRule); 
 
    } 
 
    else if(Elm.currentStyle){ 
 
     strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ 
 
      return p1.toUpperCase(); 
 
     }); 
 
     strValue = Elm.currentStyle[strCssRule]; 
 
    } 
 
    return strValue; 
 
}