1

我的 javascript 代码中有以下行:

if(document.defaultView && document.defaultView.getComputedStyle){
    strValue = document.defaultView.getComputedStyle(oElm).getPropertyValue(strCssRule);
} // ...

检索我的节点的 CSS 值(例如:)strCssRule = 'color'。它适用于火狐。它仅适用于 Chrome 上的静态页面上的简单示例。当试图将它集成到我的复杂应用程序中时,返回的每个字段CSSStyleDeclaration都是空的。

oElem使用 jQuery ( ) 检索节点oElem = $(my_selector).empty().get(0));。工作示例和我的应用程序之间的区别(至少是我能想到的唯一区别)是我的节点在计算时尚未集成到 DOM 中(仍在生成完整的 HTML)。

即使在 HTML delectation 中明确设置 CSS(例如我的节点是<div style="width:100px;"></div>)时,我也尝试过,CSSStyleDeclaration 对象仍然为空。

编辑:如 CBroe 所述,问题在于该元素尚未链接到 DOM。我想这取决于浏览器的实现如何处理这种情况。我不知道 Firefox 是如何使它工作的,但我会找到别的东西。

4

1 回答 1

1

如果你知道 CSS 规则的选择器,并且知道它是在 CSS 表单中定义的,你可以搜索它。这就是我解决这个问题的方法。

var page, rule, css;
var selector = ".my_selector";
var sheets = document.styleSheets;
for( page = 0; page < sheets.length; page++ ){
    // if you comment out this if-statement, you can search thru all of the page-wide stylesheets
    if( sheets[page].href.match(/.*\/filename\.css$/) ){
        for( rule = 0; rule < sheets[page].length; rule++ ){
            if( sheets[page][rule].selectorText === selector ){
                css = sheets[page][rule].style;
                break;
            }
        }
        break;
    }
}

// At this point, you have access to the CSS you're looking for.

console.log(css);
alert(css.backgroundColor);

// example from actual code:

if(css.borderTopWidth)this.speaker_default.edge._sizediff=Number(css.borderTopWidth.slice(0,-2));
于 2014-03-27T17:32:44.727 回答