2009-07-28 76 views
5

我有一个外部的样式表与此在它:如何访问使用外部样式表的javascript对象的样式属性?

.box { 
padding-left:30px; 
background-color: #BBFF88; 
border-width: 0; 
overflow: hidden; 
width: 400px; 
height: 150px; 
} 

然后我有这样的:

<div id="0" class="box" style="position: absolute; top: 20px; left: 20px;"> 

当我再尝试访问div的宽度:

alert(document.getElementById("0").style.width); 

出现一个空白警报框。 如何访问在我的样式表中定义的width属性?

注意:div显示正确的宽度。

+0

你可以重现问题并给我看一个测试用例吗? – 2009-07-28 11:22:41

回答

9

您应该使用window.getComputedStyle来获得该值。如果您正在查找CSS值,我建议不要使用offsetWidthclientWidth,因为它们会返回包含填充和其他计算的宽度。

使用getComputedStyle,你的代码将是:

var e = document.getElementById('0'); 
var w = document.defaultView.getComputedStyle(e,null).getPropertyValue("width"); 

该文档在MDC给出:window.getComputedStyle

2

offsetWidth显示您的div的实际宽度:

alert(document.getElementById("0").offsetWidth); 

这个宽度可以是你在你的CSS已经设置不同,虽然。 jQuery的方法是(我真的不想提他们所有的时间,但是这就是所有的库都存在于):

$("#0").width(); // should return 400 
$("#0").offsetWidth(); // should return 400 as well 
$("#0").css("width"); // returns the string 400px 
+0

简单的javascript警报不起作用。 结果未定义。 – 2009-07-28 11:39:56

0

我希望这是有帮助的:

 function changecss(theClass,element,value) { 
//Last Updated on June 23, 2009 
//documentation for this script at 
//http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html 
var cssRules; 

var added = false; 
for (var S = 0; S < document.styleSheets.length; S++){ 

if (document.styleSheets[S]['rules']) { 
    cssRules = 'rules'; 
} else if (document.styleSheets[S]['cssRules']) { 
    cssRules = 'cssRules'; 
} else { 
    //no rules found... browser unknown 
} 

    for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) { 
    if (document.styleSheets[S][cssRules][R].selectorText == theClass) { 
    if(document.styleSheets[S][cssRules][R].style[element]){ 
    document.styleSheets[S][cssRules][R].style[element] = value; 
    added=true; 
    break; 
    } 
    } 
    } 
    if(!added){ 
    if(document.styleSheets[S].insertRule){ 
      document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length); 
     } else if (document.styleSheets[S].addRule) { 
      document.styleSheets[S].addRule(theClass,element+': '+value+';'); 
     } 
    } 
} 
} 

它取自here

0

的答案大多是正确的,但将在当您尝试使用做你的头他们依赖于浏览器的渲染模式(又名严格/怪癖模式,浏览器供应商等) - 最后的答案是最好的...使用jQuery。