【发布时间】:2019-07-15 20:14:07
【问题描述】:
我不明白为什么像: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{ 不工作?
【问题讨论】:
-
仅供参考:您不应该在 Web 组件构造函数中使用参数或在构造函数中调用
super():w3c.github.io/webcomponents/spec/custom/… -
@Intervalia 谢谢。我从这里学会了这样做:developer.mozilla.org/en-US/docs/Web/Web_Components/…
标签: css html web-component shadow-dom custom-element