通过自定义属性动态更改元素样式?

时间:2015-06-24 08:41:46

标签: css polymer

例如,您可以通过更改ink来更改paper-tabs中的--paper-tab-ink: var(--accent-color);颜色。是否可以动态更改CSS自定义属性的值,类似于如何在JS中切换类或更改样式?

2 个答案:

答案 0 :(得分:1)

有不同的方法可以做到这一点,但一个简单的答案是在进行类更改后使用Polymer.updateStyles()方法。

例如,让我们说你的风格是:

<style>
.yellow x-example {
  --light-primary-color: #fdd85f;
}
.red x-example {
  --light-primary-color: red;
}
</style>

并且您希望使组件使用.red类中的样式。你只需像往常一样在javascript中添加它,然后一定要使用这个功能在页面上实际更新它。

<div class="yellow" onclick="this.className='red'; Polymer.updateStyles()">
  <x-example></x-example>
</div>

答案 1 :(得分:1)

是的,首先获取自定义元素的对象。然后获取customStyle对象。为该对象添加样式。然后运行element.updateStyles();

       t.clickListener= function(e) {
           var t = Polymer.dom(e).localTarget; //retarget if needed
           t.customStyle['--the-color-etc'] = 'pink';
           t.updateStyles(); // mandatory for the CSS variables shim
       };

请参阅the docs