Change style programmatically

吃可爱长大的小学妹 提交于 2019-12-04 08:45:14

问题


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>

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();
}

I've created a codepen demonstrating the issue


回答1:


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

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

Here's the updated codepen.



来源:https://stackoverflow.com/questions/30854101/change-style-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!