以编程方式更改样式 [英] Change style programmatically

查看:56
本文介绍了以编程方式更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循自定义属性API关于Polymer元素文档,以编程方式更新元素的CSS属性(和样式),但似乎无法使其正常工作.这是我目前的尝试:

I'm attempting to follow the Custom property API for Polymer elements docs with regards to updating an element's CSS properties (and styles) programmatically but can't seem to get it working. Here is my current attempt:

<link rel="import" href="https://rawgit.com/Polymer/polymer/master/polymer.html">

<dom-module id="my-namecard">
  <style>
    :host {
      --color: green;
    }

    span {
      color: var(--color, orange);
    }
  </style>

  <template>
    <div>
      Hi! My name is <span>{{name}}</span>
    </div>
    <button on-click="redClick">Set text to Red</button>
    <button on-click="blueClick">Set text to Blue</button>
  </template>

  <script>
    Polymer({
      is: 'my-namecard',
      properties: {
        name: {
          type: String
        }
      },
      redClick: function() {
        console.log('Setting "--color" red');
        this.customStyle['--color'] = 'red';
        this.updateStyles();
      },
      blueClick: function() {
        console.log('Setting "--color" blue');
        this.customStyle['--color'] = 'blue';
        this.updateStyles();
      }
    });
  </script>
</dom-module>

<my-namecard name="Sean"></my-namecard>

我还尝试过不设置CSS属性并使用直接样式,例如:

I've also attempted not setting a CSS property and using a direct style such as:

redClick: function() {
    console.log('Setting "color" red');
    this.customStyle['color'] = 'red';
    this.updateStyles();
}

我创建了一个 codepen 来演示此问题

I've created a codepen demonstrating the issue

推荐答案

您在当前版本的Polymer中遇到了一个错误,该错误会在这种样式更改中传播给子Polymer元素,而不传播到元素本身.参见:

You've hit a bug in the current version of Polymer, where a style change like this will propagate to child Polymer elements, but not to the element itself. See:

https://github.com/Polymer/polymer/issues/1851

解决方法是调用Polymer.updateStyles()而不是this.updateStyles().

The workaround is to call Polymer.updateStyles() instead of this.updateStyles().

这是更新的 codepen .

这篇关于以编程方式更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆