[英]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.