分两种情况讨论:
1、使用内联样式,即直接把CSS写在HTML元素的style属性中
- <div id="d1" style="width:100px;height:200px;">
- </div>
<div id="d1" style="width:100px;height:200px;">
</div>
通过以下js代码可以获取width等属性,
- alert(document.getElementById('d1').style.width);//100px
在firefox,ie,opera,safari,chrome上都可以取得到宽度和高度值。
2、使用嵌入、链入或引入样式表(非内联样式),这时候通过element.style.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.onload=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>
<!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>
最后封装到一个方法中,
- function getRealStyle(el,styName)
- {
- var len=arguments.length;
- var sty=null;
- if('currentStyle' in el){
- sty=el.currentStyle;
- }else if('getComputedStyle' in window){
- sty=window.getComputedStyle(el,null);
- }
- if(len==1){
- return sty;
- }else if(len==2){
- return sty[styName];
- }
- }