我通过以下方法修改了webcomponent的样式:
我的解决方案使用自动修改CSS自定义属性的属性。它看起来如下:
<link rel="import" href="../../bower_components/polymer/polymer.html"/>
<dom-module id="my-bar">
<template>
<style>
:host {
display: block;
box-sizing: border-box;
height: var(--my-bar-bar-height, 50%);
opacity: var(--my-bar-bar-opacity, 0.8);
border: var(--my-bar-bar-border, 1px solid black);
width: 100%;
}
div {
background-color: var(--my-bar-bar-color, blue);
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
<div id="bar"></div>
</template>
<script>
Polymer({
is: 'my-bar',
properties: {
barColor: {
type: String,
observer: '_colorChanged'
},
barHeight: {
type: String,
observer: '_heightChanged'
},
barOpacity: {
type: String,
observer: '_opacityChanged'
},
barBorder: {
type: String,
observer: '_borderChanged'
}
},
_heightChanged: function () {
this._styleChanged("barHeight");
},
_colorChanged: function () {
this._styleChanged("barColor");
},
_opacityChanged: function () {
this._styleChanged("barOpacity");
},
_borderChanged: function () {
this._styleChanged("barBorder");
},
_styleChanged: function(name) {
// update the style dynamically, will be something like:
// this.customStyle['--my-bar-bar-color'] = 'red';
this.customStyle[this._getCSSPropertyName(name)] = this[name];
this.updateStyles();
},
_getCSSPropertyName: function(name) {
// retrieves the CSS custom property from the Polymer property name
var ret = "--" + this.is + "-";
var char = "";
for(i = 0; i < name.length; i++)
{
char = name.charAt(i);
if(char >= 'A' && char <= 'Z') {
ret += "-" + char.toLowerCase();
}
else {
ret += char;
}
}
return ret;
}
});
</script>
</dom-module>然后,您可以使用CSS样式:
my-bar {
--my-bar-bar-color: gray;
}通过HTML:
<my-bar bar-height="20%" bar-opacity="0.1" bar-border="2px solid black"></my-bar>或者JavaScript:
this.$.my-bar.barHeight = "20%;向API添加新的CSS属性意味着添加以下行:
_styleChanged()的观察者代码我不认为在聚合物中,你可以用传递给观察者的函数来指定变量或常数,所以这就是为什么第二点是必要的。
是否有更好的方法为聚合物创建CSS风格的API?我能做什么改进或简化吗?
https://stackoverflow.com/questions/38370535
复制相似问题