[英]How do I select the shadow DOM host element only if it is the last-child?
我正在寻找 select 阴影 DOM 宿主元素,前提是它是最后一个子元素。
在这个例子中,它们都是绿色的,我希望它们都是红色的,除了最后一个。
class MyCustomElement extends HTMLElement { constructor(){ super(); this.attachShadow({mode: 'open'}); this.shadowRoot.innerHTML = ` <h5>Element:</h5> <slot></slot> <style>:host { color: red; }:host-context(:last-child) { color: green; } </style> `; } } window.customElements.define('my-custom-element', MyCustomElement);
<div> <my-custom-element>first</my-cutom-element> <my-custom-element>... more elements</my-cutom-element> <my-custom-element>last</my-cutom-element> </div>
这些都是绿色的……我只希望最后一个是绿色的。
我也尝试过:host:last-child
,它什么都不做, :host-context(my-custom-element:last-child)
也使它们全部变成绿色。
从我的其他答案中获取指针: 使用 CSS 选择器,例如:影子 dom 中的第一个孩子
您的元素仍然隐藏在 lightDOM 中!
您应用的任何全局样式(在任何时候)都将反映到 shadowDOM
customElements.define('my-custom-element', class extends HTMLElement { constructor(){ super().attachShadow({mode: 'open'}).innerHTML = `<slot></slot><style>:host { color: red; }</style>`; } });
<div> <my-custom-element>first</my-custom-element> <my-custom-element>... more elements</my-custom-element> <my-custom-element>last</my-custom-element> </div> <style> div my-custom-element:last-child { padding: .5em; background: green; } </style>
笔记:
super()
返回 'this' (元素本身),所以你可以链接它
attachShadow 返回this.shadowRoot
,所以你可以链接它
FireFox 和 Safari 将不支持您提到的:host-context
请参阅: :host-context 在 Lit-Element web 组件中未按预期工作
这可能是真正的答案,但这是一个无赖,我认为影子 dom 的整个要点是自包含的,如果我必须在全局样式表中编写一些 styles 然后在影子 dom 中设置一些样式看起来没什么大不了的,难怪当 web 标准如此糟糕时,人们会倾向于 react 和 vue 之类的东西。
这样想吧。 如果您的my-custom-element
在<p>
元素中; <p>
怎么会知道它在last-child
里面......只有通过引用它的父容器。
如果您不希望该容器成为全局 scope,则:
使用 shadowDOM 将所有内容包装在另一个元素中
插槽my-custom-element
并使用: ::slotted(:last-child)
定位最后一个
https://jsfiddle.net/CustomElementsExamples/aLezyh35/
或者将元素从 ligthDOM 移动到 shadowDOM
https://jsfiddle.net/CustomElementsExamples/v2f9zmu5/
难怪当 web 标准如此糟糕时,人们会倾向于 React 和 Vue 之类的东西。
所有框架都做同样的事情,它们将事物包装在容器中(无论是在常规 DOM、shadowDOM、虚拟 DOM(内存)中)
更好的说法:框架将您的内容框架在容器中......总是
原生 W3C 标准自定义元素 API 提供100% 控制是否使用容器。
是的,这意味着您必须先编写脚本/烹饪,然后才能用餐。
您可以 100% 自由地烹饪组件。
React 为您的下载增加了48 KB (GZipped),更不用说整个构建过程,更不用说它永远不会与任何其他框架协同工作,更不用说它甚至不再符合ES 标准。
一个额外的自定义元素需要大约 15 分钟,可能需要 200个字节
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.