javascript - 使用 CSS 引用 Web 组件根属性
问题描述
创建了一个带有影子 DOM 的 Web 组件。单击按钮时,它会将open
属性添加到 Web 组件。
open
当添加 CSS 样式时,我想在 CSS 中显示隐藏的 div 。阴影 DOM 样式是否可以引用 Web 组件根目录上的属性?否则,我必须在影子 DOM 中添加一个多余的类或属性。
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);
<template id="custom-component">
<style>
div {
display: none;
}
[open] div {
display: block;
}
</style>
<button>Open</button>
<div>Content</div>
</template>
<custom-component></custom-component>
解决方案
看来host
CSS 伪选择器旨在处理这种精确情况。
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);
<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>
推荐阅读
- html - 如何使多个 SVG 内联?
- php - MongoDB PECL 驱动程序和 Composer PHPLIB 之间的区别?
- python - 如何在散景图中旋转箭头标记以显示风速方向?
- java - RDDs如何为自己拆分数据?
- ruby-on-rails - 设置to_param方法后无法创建嵌套资源
- ios - 如何获取我的 iOS 应用程序的本地化语言?
- python - python中的平均风数据(每小时10-10分钟)
- css - 如何从 CSS font-family 列表中知道浏览器使用哪种字体?
- firebase - 建立 Firebase 聊天室数据库很热门?
- jackrabbit - 长耳兔聚类