为什么宿主元素上的伪类必须位于宿主函数内部?

2023-12-13

我不明白为什么伪类喜欢: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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么宿主元素上的伪类必须位于宿主函数内部? 的相关文章