如何在自定义元素中提供回退 CSS 值?



我有一个自定义的Web组件,它基本上是一个SVG图标:

<custom-icon>
<svg>{svg-stuff}</svg>
</custom-icon>

我希望能够通过应用CSS来更改它的大小,如下所示:

custom-icon {
width: 20px;
}

但是我也希望在未应用 CSS 时有一个回退默认值。但是,当我内联一些像<custom-icon style="width:15px">这样的 CSS 时,它只会覆盖我之后应用的所有 CSS。如何在没有自定义 CSS 的情况下才应用默认的"15px"?

女工程师:

class CustomIcon extends HTMLElement {
constructor() {
super();

let size = "100px"

this.style.height = size;
this.style.width = size;

this.style.background = "firebrick"
this.style.display = "block"
}
}
window.customElements.define('custom-icon', CustomIcon);
custom-icon {
--icon-size: 50px;
height: var(--icon-size);
width: var(--icon-size);
}
<custom-icon />

如果自定义元素的内容封装在 Shadow DOM 中(这是建议的做法(,则可以使用:host伪类来定义默认样式。

然后,如果您为自定义元素定义全局样式,它将覆盖使用:host定义的样式。

customElements.define( 'custom-icon', class extends HTMLElement {
constructor() {
super()
let size = 100
this.attachShadow( { mode: 'open' } )
.innerHTML = `
<style>
:host {
display: inline-block ;
height: ${size}px ;
width: ${size}px ;
background-color: firebrick ; 
color: white;
}
</style>
<slot></slot>`
}
} )
custom-icon#i1 {
--icon-size: 50px;
height: var(--icon-size);
width: var(--icon-size);
}
<custom-icon id="i1">sized</custom-icon>
<hr>
<custom-icon>default</custom-icon>

根据级联应用顺序。

通过style属性应用的 CSS 位于级联的底部。实际上,如果您没有通过属性指定何时回退到样式表。

因此,当您不指定15px时,20px是回退。


您可以使用另一个规则集编写回退 CSS,该规则集具有不太具体的选择器(尽管唯一比单个类型选择器(如custom-icon(更具体的是通用选择器 (*(,这没有帮助(,因此您需要用具体的东西替换custom-icon

另一种选择是采用大锤方法,使规则集中的每一条规则都!important


最好的选择可能是首先修复可能导致您的 CSS 丢失的任何情况。

您可以考虑数据属性,然后将该属性用作自定义属性的回退。

您可以在下面看到,在我们删除自定义属性(通过设置initial(之前,大小将不起作用

class CustomIcon extends HTMLElement {
constructor() {
super();

this.style.height = `var(--icon-size, ${this.getAttribute('size')})`;
this.style.width = `var(--icon-size, ${this.getAttribute('size')})`;

this.style.background = "firebrick"
this.style.display = "block"
}
}
window.customElements.define('custom-icon', CustomIcon);
custom-icon {
--icon-size: 50px;
margin:5px;
}
<custom-icon size="15px"></custom-icon>
<custom-icon size="25px"></custom-icon>
<custom-icon size="2050px"></custom-icon>
<custom-icon size="200px" style="--icon-size:initial"></custom-icon>

了解initial使用的相关问题:盒子模型的CSS自定义属性(变量(

最初未设置自定义属性的另一个示例。

class CustomIcon extends HTMLElement {
constructor() {
super();
this.style.height = `var(--icon-size, ${this.getAttribute('size')})`;
this.style.width = `var(--icon-size, ${this.getAttribute('size')})`;
this.style.background = "firebrick"
this.style.display = "block"
}
}
window.customElements.define('custom-icon', CustomIcon);
custom-icon {
margin: 5px;
}
.set {
--icon-size: 50px;
}
<div class="set">
<custom-icon size="15px"></custom-icon>
<custom-icon size="25px"></custom-icon>
<custom-icon size="2050px"></custom-icon>
</div>
<custom-icon size="200px" ></custom-icon>

最新更新