首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CSS引用web组件根属性

使用CSS引用web组件根属性
EN

Stack Overflow用户
提问于 2020-09-12 01:22:08
回答 1查看 29关注 0票数 1

创建了一个带有阴影DOM的web组件。单击该按钮时,它会将open属性添加到web组件。

我想在CSS中显示隐藏的div,当open添加CSS样式时。阴影DOM样式是否可以引用web组件根目录上的属性?否则,我必须在阴影DOM中添加一个多余的类或属性。

代码语言:javascript
复制
class CustomComponent extends HTMLElement {
  constructor() {
    super();
    
    this.element = this.attachShadow({mode: 'open'});
  }
  
  static get observedAttributes() {
    return ['open'];  
  }
  
  attributeChangedCallback(attrName, oldValue, newValue) {
    if (newValue !== oldValue) {
      this[attrName] = this.hasAttribute(attrName);
    }
  }
  
  connectedCallback() {
    const template = document.getElementById('custom-component');
    const node = document.importNode(template.content, true);
    this.element.appendChild(node);
    
    this.element.querySelector('button').addEventListener('click', () => {
      this.setAttribute('open', '');
    });
  }
}

customElements.define('custom-component', CustomComponent);
代码语言:javascript
复制
<template id="custom-component">
  <style>
    div {
      display: none;
    }
    [open] div {
      display: block;
    }
  </style>
  <button>Open</button>
  <div>Content</div>
</template>

<custom-component></custom-component>

EN

回答 1

Stack Overflow用户

发布于 2020-09-12 01:30:23

似乎host CSS伪选择器就是为处理这种精确的情况而设计的。

代码语言:javascript
复制
class CustomComponent extends HTMLElement {
  constructor() {
    super();
    
    this.element = this.attachShadow({mode: 'open'});
  }
  
  static get observedAttributes() {
    return ['open'];  
  }
  
  attributeChangedCallback(attrName, oldValue, newValue) {
    if (newValue !== oldValue) {
      this[attrName] = this.hasAttribute(attrName);
    }
  }
  
  connectedCallback() {
    const template = document.getElementById('custom-component');
    const node = document.importNode(template.content, true);
    this.element.appendChild(node);
    
    this.element.querySelector('button').addEventListener('click', () => {
      this.setAttribute('open', '');
    });
  }
}

customElements.define('custom-component', CustomComponent);
代码语言:javascript
复制
<template id="custom-component">
  <style>
    div {
      display: none;
    }
    :host([open]) div {
      display: block;
    }
  </style>
  <button>Open</button>
  <div>Content</div>
</template>

<custom-component></custom-component>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63851645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档