gpt4 book ai didi

css - 为什么宿主元素上的伪类必须在宿主函数内部?

转载 作者:太空宇宙 更新时间:2023-11-04 14:50:06 24 4
gpt4 key购买 nike

我不明白为什么像 :focus-within 这样的伪类在作用于主机本身时需要在 :host() 函数括号内。为什么不能是:host:focus-within div?更奇怪的是它在另一个 :host() 中的 :host 上工作。

class MyElementFail extends HTMLElement {

constructor(...args) {
super(...args)

this.attachShadow({mode: 'open'}).innerHTML = `
<style>
:host{
display: block;
padding: 20px;
background-color: salmon;
}
:host div{
background-color: white;
}
/*This part is different:*/
:host:focus-within div{
background-color: green;
}
</style>
<input type="text" value="click in here"/>
<div>
Change to green
</div>`
}
}
window.customElements.define('my-element-fail', MyElementFail);


class MyElement extends HTMLElement {

constructor(...args) {
super(...args)

this.attachShadow({mode: 'open'}).innerHTML = `
<style>
:host{
display: block;
padding: 20px;
background-color: salmon;
}
:host div{
background-color: white;
}
/*This part is different:*/
:host(my-element:focus-within) div{
background-color: green;
}
</style>
<input type="text" value="click in here"/>
<div>
Change to green
</div>`
}
}
window.customElements.define('my-element', MyElement);


class MyElementTwo extends HTMLElement {

constructor(...args) {
super(...args)

this.attachShadow({mode: 'open'}).innerHTML = `
<style>
:host{
display: block;
padding: 20px;
background-color: salmon;
}
:host div{
background-color: white;
}
/*This part is different:*/
:host(:host:focus-within) div{
background-color: green;
}
</style>
<input type="text" value="click in here"/>
<div>
Change to green
</div>`
}
}
window.customElements.define('my-element-two', MyElementTwo);
No Good:
<my-element-fail></my-element-fail>
Good:
<my-element></my-element>
Good also:
<my-element-two></my-element-two>

本质上,为什么,

:host(:host:focus-within) div{ 工作,并且

:host(my-element:focus-within) div{ 有效,但是

:host:focus-within div{ 不起作用?

最佳答案

:host只是表示shadowDOM的宿主元素。

:host(.something) 表示主机类为.something

你不能使用 :host.something 你必须使用括号。

:host() 不是函数。这只是如何选择具有额外特异性的 :host

class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'}).innerHTML = `
<style>
:host{
display: block;
padding: 20px;
background-color: salmon;
}

div{
background-color: white;
}

:host(:focus-within) div{
background-color: green;
}
</style>
<input type="text" value="click in here"/>
<div>Change to green</div>`;
}
}
window.customElements.define('my-element', MyElement);
<my-element></my-element>

关于css - 为什么宿主元素上的伪类必须在宿主函数内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com