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

How can I get StyleSheet css rules using webcomponent.js

本文关键字:样式 css 规则 何使用 webcomponent js      更新时间:2023-09-26

我最近正在编写一个web组件,现在尝试为其他不支持的浏览器添加webcomponentsjs多边形,但是当我使用它时我有一个问题。

我必须得到一个childNodes样式表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?

问题是,我怎么能得到cssRules?

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

谢谢。

无论是否使用Shadow DOM,方法都是不同的。

在polyfill 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'
    } )
}