【问题标题】:How can I add a class based on a property in lit-element?如何根据 lit-element 中的属性添加类?
【发布时间】:2020-07-01 10:15:56
【问题描述】:

如何使用 Web 组件属性添加条件类?所以假设我有一个图像组件,它获取属性 fullscreen 然后我想将类 fullscreen 添加到我的组件(使用 lit 元素);

我现在拥有的(不工作)

export class Image extends LitElement{
static get styles() {
    return css `
  :host {
    display: block;
    height: 100%;
  }

  picture {
      display: block;
  }

  .fullscreen img {
      position: absolute;
      object-fit: cover;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      height: 100%;
      width: 100%;
      z-index: -2;
  }
`;
}

static get properties() {
    return {
        fullScreen: {
            type: Boolean
        },
        imageSrc: {
            type: String
        }
    };
}

constructor() {
    super();
    this.fullScreenClass = {
        fullscreen: this.fullScreen
    }
    this.imageSrc = "";
}

render() {
    return html `
    <picture class=${classMap(this.fullScreenClass)}>
    <source
    srcset="${this.imageSrc}">
  <img scr="${this.imageSrc}">
    </picture>
`;
}

}

我想如何使用它

<test-image fullscreen
  imageSrc="https://www.driving.co.uk/s3/st-driving-prod/uploads/2019/05/Aston-Martin-Rapide-E-Charging-01.jpg">
</test-image>

【问题讨论】:

    标签: polymer web-component lit-element


    【解决方案1】:

    你可以使用属性 css 选择器

    :host([fullscreen]) {
        // your styling for fullscreen
      }
    

    由于fullscreen 属性,此样式将应用于 HTML 中的以下组件实例

    <test-image fullscreen
      imageSrc="https://www.driving.co.uk/s3/st-driving-prod/uploads/2019/05/Aston-Martin-Rapide-E-Charging-01.jpg">
    </test-image>
    

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2023-03-09
      • 1970-01-01
      • 2021-07-29
      • 2022-09-13
      • 2021-04-10
      相关资源
      最近更新 更多