阴影根或阴影根中所有顶级元素的CSS选择器 [英] CSS selector for shadow root or all top level elements in shadow root

查看:128
本文介绍了阴影根或阴影根中所有顶级元素的CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个选择器以在影子根内部的CSS中使用,该选择器选择影子根的所有子级(但不是大子级),无论它们是什么标签且都没有给它们提供ID.

在下面的示例中,SPAN,A,P和DIV应该显示红色边框,但SPAN IN DIV不会显示红色边框.

<my-element>
  #shadow-root
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :root>*{border:1px red solid;}
    </style>
</my-element>

我希望:root -Selector可以在影子dom内完成这项工作,但事实并非如此.

如果有人展示了如何在影子根上设置ID,这也是一种可能的解决方案.

更新:

尝试使用#shadow-root > *作为选择器:

似乎不起作用.可能只是google chrome开发人员工具可视化像这样的影子根元素.

解决方案

使用此选择器::host > *

:host选择器在 https://drafts.c​​sswg.org中进行了描述/css-scoping/#host-selector

 document.querySelector( 'my-element' )
  .attachShadow( { mode: 'open' } )
  .innerHTML = `
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :host>*{border:1px red solid;}
    </style>` 

 <my-element>
</my-element> 

:host也可能包含一个复合选择器,该选择器必须放在方括号中.例如. :host([foo=bar])选择将属性foo设置为bar的宿主元素.

I need a selector for usage in css inside a shadow root, which selects all children (but not grand children) of the shadow root, no matter what tag they are and without giving them an ID.

In the example below, SPAN,A,P and DIV should get a red border, but SPAN IN DIV not.

<my-element>
  #shadow-root
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :root>*{border:1px red solid;}
    </style>
</my-element>

I hoped, the :root-Selector would do the job inside of a shadow dom, but thats not the case.

It would also be a possible solution if someone shows how to set an ID on the shadow root.

Update:

Tried using #shadow-root > * as selector:

seems not to work. Probably it is just google chrome developer tools visualizing the shadow root element like that.

解决方案

Use this selector: :host > *

The :host selector is described in https://drafts.csswg.org/css-scoping/#host-selector

document.querySelector( 'my-element' )
  .attachShadow( { mode: 'open' } )
  .innerHTML = `
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :host>*{border:1px red solid;}
    </style>`

<my-element>
</my-element>

:host may also hold a compound selector, which must be places in brackets. E.g. :host([foo=bar]) selects a host element which has attribute foo set to bar.

这篇关于阴影根或阴影根中所有顶级元素的CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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