0

当使用 webcomponents-lite this.updateStyles 按预期工作。但是在不需要它的浏览器上,我不想加载它。

this.updateStyles 应该在没有 webcomponents-lite 的情况下工作吗?

非工作版本示例: http ://codepen.io/daKmoR/pen/dNPdya

class XFoo extends Polymer.Element {
    static get is() { return 'x-foo'; }

    static get config() {
        return {
            properties: {
                width: {
                    type: String,
                    reflectToAttribute: true,
                    observer: '_onWidthChange'
                }
            }
        };
    }

    constructor() {
        super();
    }

    _onWidthChange(newValue, oldValue) {
        console.log('setting width');
        this.updateStyles({'--width': newValue});
    }

}
customElements.define(XFoo.is, XFoo);

使用自己的 updateStyles 的解决方法示例:http: //codepen.io/daKmoR/pen/ggbeaR

class XFoo extends Polymer.Element {
    static get is() { return 'x-foo'; }

    static get config() {
        return {
            properties: {
                width: {
                    type: String,
                    reflectToAttribute: true,
                    observer: '_onWidthChange'
                }
            }
        };
    }

    constructor() {
        super();
    }

    _onWidthChange(newValue, oldValue) {
        console.log('setting width');
        this.updateStyles({'--width': newValue});
    }

    updateStyles(obj) {
        if (obj === undefined) {
            return;
        }
        var str = '';
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += p + ': ' + obj[p] + ';';
            }
        }
        this.style = str;
    }    

}
customElements.define(XFoo.is, XFoo);

有没有更好的办法?

4

1 回答 1

0

因为我需要支持带有 CSS 自定义属性的内联样式,即使是 IE11,IE Edge 我也为它创建了自己的行为。

简而言之:

  • 将内联样式写入样式和数据样式(因为样式将删除 IE11、IE Edge 中的所有未知属性)
  • 读取数据样式并使用 ShadyCSS.updateStyles

你可以在这里查看 https://www.webcomponents.org/element/daKmoR/grain-update-inline-style-behavior

于 2017-04-30T23:32:57.237 回答