我的<web-component></webcomponent>
是很简单搭建的,<input type="text part="input" />
系列直接在#shadow-root
.
我可以一口气把它们都做好,没有任何问题:
web-component::part(input) {
border: 1px solid #000
}
但如果我想要针对特定的输入,这两种方法都不起作用:
web-component::part(input):nth-child(3) {}
web-component::part(input):nth-of-type(3) {}
web-component::part(input).input-3 {} /* with class properly defined in the web component */
web-component::part(input.input-3) {}
web-component::part(input:nth-of-type(3)) {}
...
找不到任何有关此问题的文档.
编辑:我忘了提到,输入不是时隙,它们是动态生成的.
customElements.define("web-component",
class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"});
this.size = this.getAttribute('size');
this.template = document.createElement("template");
this.template.innerHTML = '<style>'
+':host {white-space: nowrap}'
+'input {text-align:center;width: 3ch;height: 3ch}'
+'input:not(:last-child){margin-right:.5ch}'
+'</style>'
this.render();
}
render() {
this.shadowRoot.appendChild(this.template.content.cloneNode(true));
for (let i = 0; i < this.size; i++) {
const input = document.createElement('input');
input.setAttribute('part','input');
input.classList.add('input-'+(i+1));
input.type = "text";
this.shadowRoot.appendChild(input);
}
}
}
);
web-component::part(input) {
border: 2px solid orange;
}
web-component::part(input):nth-child(1) {
background: #ff00ff;
}
web-component::part(input):nth-of-type(2) {
background: #ff0000;
}
web-component::part(input).input-3 {
background: #00ff00;
}
web-component::part(input.input-4) {
background: #00ffff;
}
web-component::part(input:nth-of-type(5)) {
background: #ff00ff;
}
web-component::part(input:nth-chlid(6)) {
background: #ff0000;
}
<web-component size="6"></web-component>