简体   繁体   English

如何使用webcomponent.js获取StyleSheet css规则

[英]How can I get StyleSheet css rules using webcomponent.js

I'm coding a web component recently, and now try to add webcomponentsjs polyfills for other unsupported browser, but I have a problem when I'm using it. 我最近正在编写一个Web组件,现在尝试为其他不受支持的浏览器添加webcomponentsjs polyfills,但是当我使用它时我遇到了问题。

I have to get a childNodes stylesheet css rules for dynamic changes, the code here works fine in chrome: 我必须获得动态更改的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;
                }
           }
        }

The problem is I can't access node[1]['sheet'].cssRules in webcomponentsjs in firefox and safari, since it's inside one more layer Object { __impl4cf1e782hg__: <template> ... } , although I get inside to it ['__impl4cf1e782hg__'] , but I'm not allow to get anything. 问题是我无法访问node[1]['sheet'].cssRules在firecomp和safari中的node[1]['sheet'].cssRules中的cssRules,因为它在一个Object { __impl4cf1e782hg__: <template> ... } ,尽管我进入它['__impl4cf1e782hg__'] ,但我不允许得到任何东西。 How to change this code for webcomponentsjs? 如何更改webcomponentsjs的此代码?

Question is, how can I get cssRules? 问题是,我怎样才能获得cssRules?

I can't see any information about getting sheet in their website. 我看不到有关在他们的网站上获取表单的任何信息。 Have any ideas? 有什么想法吗?

Thank you. 谢谢。

The method is different whether you use Shadow DOM or not. 无论您是否使用Shadow DOM,该方法都是不同的。

A way for accessing the sheet inside the polyfilled Shadow DOM is to use the setTimeout() function in the attachedCallback() method, because it's only after that moment that the stylesheet becomes available. 在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'
    } )
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM