在阴影dom内使用:first-child之类的CSS选择器 [英] Use CSS selectors like :first-child inside shadow dom

查看:113
本文介绍了在阴影dom内使用:first-child之类的CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阴影dom内是否可以使用诸如:first-child,:not(:last-child)之类的css选择器?

Is there any way to use css selectors like :first-child, :not(:last-child) inside of the shadow dom?

示例类似于此

CustomElement.html

CustomElement.html

<div id="parent-div>
 <slot></slot>
</div>

App.html

<div>
 <custom-element>
   <div class="heading">Main Heading</div>
   <div class="item">item 1</div>
   <div class="item">item 1</div>
   <div class="item">item 1</div>
   <div class="heading">Second Heading</div>
   <div class="item">item 1</div>
   <div class="item">item 1</div>
   <div class="item">item 1</div>
 </custom-element>
</div>

我要做的是找出第一个.heading元素并为其添加自定义样式。 < div class = heading> 实际上是一个组件,我不能向其添加自定义样式,仅将其作为第一个标题。

what i want to do is find out the first .heading element and add custom styles to it. Since <div class=heading"> is actually a component, i can't add custom styling to it thinking only as the first heading.

PS:-我正在使用角度元素,如果有帮助

P.S.:- I'm using angular-elements, if it helps

推荐答案

我发现了一个解决方法为 JS方式

I found a workaround for this in JS way.

对于每个插槽,我们都有一个名为(slotchange)的eventHandler。通过使用它,只要插槽更改,我们就可以获取该插槽的DOM事件。像这样(HTML)

For each slot, we have a eventHandler called (slotchange). By using that we can get the DOM event for the slot whenever the slot changes. Like this (HTML)

<custom-element (slotchange)="onSlotChanged($event)"></custom-element>

JS

onSlotChanged($event) {
 console.log($event) // Go and research yourself about this event, you'll find many things usefull.
 $event.target.assignedNodes() // This will give you the array of every elements, that are in side of the shadow dom
 // Example usage, adding the margin-bottom to only first time (css :firsh-child)
 $event.target.assignedNodes()[0].shadowRoot.getElementById('some-id').style.marginBottom = '10px'
}

如果只需要向元素添加属性,则不必查询shadowDom,例如 node.shadowRoot 。但是,如果要访问该元素的shadowRoot内部的元素,则必须使用该

If you only need to add a property to the element, you don't have to query shadowDom like "node.shadowRoot". But, if you want to access the element inside the shadowRoot of that element, you have to use that

这篇关于在阴影dom内使用:first-child之类的CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆