我不明白为什么像 :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>
我是一名优秀的程序员,十分优秀!