如何使用 webcomponent.js 获取样式表 css 规则

How can I get StyleSheet css rules using webcomponent.js

我最近在写一个web组件,现在尝试为其他不支持的浏览器添加webcomponentsjs polyfills,但是我在使用时遇到了问题。

我必须得到一个子节点样式sheet css动态变化的规则,这里的代码在chrome中工作正常:

        node = this['root'].childNodes;
        //this['root']: is <template> element
        //Here is webcomponentjs console.log in Firefox:
        //Object
        // { __impl4cf1e782hg__: <template#sd>,
        //          parentNode_: undefined, firstChild_: undefined, 
        //          lastChild_: undefined, nextSibling_: undefined, 
        //          previousSibling_: undefined, treeScope_: Object }

        style = node[1]['sheet'].cssRules;

        if(bgColor || hairColor){
            for(i = 0; i < style.length; i++){
                if(style[i].selectorText === '.base'){
                    style[i].style.background = bgColor;
                }
                if(style[i].selectorText === '.hair'
                   || style[i].selectorText === '.hair::before'
                   || style[i].selectorText === '.hair::after' ){
                    style[i].style.background = hairColor;
                }
           }
        }

问题是我无法在 firefox 和 safari 中的 webcomponentsjs 中访问 node[1]['sheet'].cssRules,因为它在另一层 Object { __impl4cf1e782hg__: <template> ... } 内,虽然我进入了它 ['__impl4cf1e782hg__'] ,但是我不允许得到任何东西。如何更改 webcomponentsjs 的代码?

问题是,如何获得css规则?

我在他们的网站上看不到有关获得 sheet 的任何信息。有什么想法吗?

谢谢。

无论是否使用ShadowDOM方法都不一样

在 polyfilled Shadow DOM 中访问 sheet 的一种方法是在 attachedCallback() 方法中使用 setTimeout() 函数,因为只有在那一刻之后样式表可用。

prototype.attachedCallback = function ()
{
    var style = this.shadowRoot.querySelector( 'style' )

    setTimeout( function () 
    { 
        var sheet = style.sheet
        console.info( 'sheet is ok =>', sheet )
        //you can modify styles here:
        sheet.cssRules[0].style.color = 'dodgerblue'
    } )
}