如何使用 JS 函数在 Polymer 3 中设置 CSS 样式

How to set CSS style in Polymer 3 using JS functions

所以,我是 Polymer 的新手,但我已经学习了所有我能找到的教程,而且搜索功能也无法帮助我解决我的问题。

我正在尝试通过 JS 函数设置元素的样式。我知道我可以使用类似的东西:

getColor () {
  if(this.is_even) {
    return  "background-color: green;";
  }
  else {
    return "background-color: red;";
  }
}

static get template() {
  return html`
    <div class="icon" style$="[[getColor()]]"></div>
  `
}

根据图标 "is_even" 属性 设置图标的背景颜色。我的问题是:我也可以在 css 样式标签中这样做吗?是否有这样的等效语法:

.icon
{
  $[[getColor()]]
}

或者也许

.icon
{
  background-color$: [[getColor()]];
}

我试图通过这种语法根据特定条件编辑“:host”元素的样式,但我找不到任何相关信息。

提前致谢:)

这里是如何使用 css 的示例:

DEMO

static get template() {
return html`
  <style> 
  .cfalse {
    background-color: red;
  }

  .ctrue {
    background-color: green;
  }
  </style>

  <div class$="icon c[[is_even]]"></div>
`;
}

你可以和观察者一起做:

static get observers() {
  return [
    'checkColor(is_even)'
  ]
}

checkColor(e) {
  this.set('getColor', !!e ? "background-color: green;" : "background-color: red;" );

  }

static get template() {
  return html`
    <div class="icon" style$="[[getColor]]"></div>` }

或者您可以将观察者设置为 属性 减速:

static get properties() {
    return {
      is_even: {
        type: Boolean,
        // Observer method identified by name
        observer: 'checkColor'
      }
    }
  } 

编辑:也可以利用 Polymer Lit Element 的优势渲染 html 样式。为了使用 lit 元素

import { LitElement, html } from '@polymer/lit-element'; 

然后在扩展您的自定义元素后点亮元素的 class :

class MyElement extends LitElement {
  static get properties(){.....
 ....

最后:

${this.is_even?
  html`<div class="icon" style="background-color: green;"></div>`:
  html`<div class="icon" style="background-color: red;"></div>`}

有关 litElement 的更多信息