javascript 擷取特定的 CSS屬性值

來源:互聯網
上載者:User

<link id="system_style" type="text/css" href="global.css" rel="stylesheet"/>
<div id="myArticle">
...
</div>

  在global.css中聲明了

#myArticle{
width:400px;
height:300px;
}

  這樣的情況下,直接通過JS進行getElementById('myArticle').style.width是無法擷取400px的值的,因為這個數值定義在CSS裡,所以,必須要用其他方法,我寫了以下函數:

/**
* function for get the style value in special css file
* @param int css_file_id
* @param String labname
* @param String param
*/
function getStyleValue(css_file_id,labname,param)
{
var tar;
var rss;
var style;
var value;

tar = document.styleSheets[css_file_id];

rss = tar.cssRules?tar.cssRules:tar.rules

for(i=0;i<rss.length;i )
{
style = rss[i];
if(style.selectorText.toLowerCase() == labname.toLowerCase())
{
value = style.style[param];
}
}
return value;
}

  現在只要通過

getStyleValue(0,'#myArticle','width')

  就可以獲得啦:)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.