[英]How can I access style properties on javascript objects which are using external style sheets?
我有一个外部样式表:
.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显示正确的宽度。
您应该使用window.getComputedStyle
来获取该值。 如果你正在寻找CSS值,我建议不要使用offsetWidth
或clientWidth
,因为那些返回包含填充和其他计算的宽度。
使用getComputedStyle
,您的代码将是:
var e = document.getElementById('0');
var w = document.defaultView.getComputedStyle(e,null).getPropertyValue("width");
MDC上提供了相关文档: window.getComputedStyle
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
我希望这是有帮助的:
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+';');
}
}
}
}
它取自这里 。
答案大多是正确的,但是当你尝试使用它们时它们会依赖于它们依赖于浏览器的渲染模式(又称严格/怪癖模式,浏览器供应商等) - 最后的答案是最好的......使用jquery。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.