方法一:
用途:用于获得在CSS文件中声明的特定样式中的某属性值。如:
<link id="system_style" type="text/css" href="global.css" rel="stylesheet"/>
<div id="myArticle" style="left:10px;top:35px;" >
在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')
就可以获得啦:)
方法二:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>b.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
#d2 {
width:400px;
height:200px;
border:5px solid gray;
padding:5px;
}
</style>
<script>
window.οnlοad=function(){
//2、使用嵌入、链入或引入样式表(非内联样式)
//ie:通过currentStyle
alert(document.getElementById('d2').currentStyle.width);//400px ie
//ff,safari,opera,chrome:通过window.getComputedStyle
var el=document.getElementById('d2');
alert(window.getComputedStyle(el,null).style.width);//400px safari,opera,chrome
}
</script>
</head>
<body>
<div id="d2"></div>
</body>
</html>
方法三:
如果样式直接用style写在前台如:
<div id="div1" runat="server" style="height:100px;"></div>
在后台可以使用
string str = div1.Style["height"];
来获得