CSS:如何在Shadow DOM根中定位::slotted兄弟元素?

16

我知道当前规范仅允许在::slotted中使用复合选择器,即 ::slotted(my-first + my-second) 不被允许,但是类似这样的语法是否可行?

::slotted(x-first) + ::slotted(x-second) { /* css */ }

有没有办法针对“slot”元素的兄弟元素进行样式定位(除了使用全局CSS)?如果没有,我应该在哪里提交此类请求?谢谢。


这与 ::slotted(x-first + x-second) 有何不同? - Supersharp
2个回答

20

当然,您可以选择siblingsslots / slotted

您不能做的是选择一个已被放置并且不是顶级节点的元素。

选择同级:

slot[name=<slotname>] ~ <selector>

选择插槽的顶级节点

::slotted(<compound-selector>)

复合选择器包含标签/类/ID/名称等等,但不得有任何组合器。例如,像<space>这样的。

.myClass 可以

<anyTag>[<anyAttribute>[=<anyValue>]] 可以

.<myClass> > .<anotherClass> 不可以

例子

var element = document.querySelector('.templateMe');
var shadow = element.attachShadow({mode: 'open'});
var template = document.querySelector('.myTemplate');
shadow.appendChild(template.content.cloneNode(true));
<template class="myTemplate">
  <style type="text/css">
    ::slotted([slot=slot1]) { /* slot1 every slotted element - YES */
      color: red;
    }
    
    slot[name=slot1] { /* slot1 itself - YES */
      text-decoration: underline;
    }
    
    slot[name=slot1] + .siblingA { /* slot1 siblingA (direct sibling) - YES */
      color: green;
    }
    
    slot[name=slot1]  ~ .siblingB { /* slot1 siblingB (any sibling) - YES */
      color: orange;
    }
    
    slot[name=slot2]::slotted(.selectMeA) { /* slot2 TOP-LEVEL CHILD (slotted) - YES */
      color: purple;
    }
    
    slot[name=slot2]::slotted(.selectMeB) { /* slot2 NOT TOP-LEVEL CHILD - NO */
      font-weight: bold;
    }
    
    slot[name=slot2]::slotted(.selectMeC[name=myName]) { /* slot2 TOP-LEVEL CHILD (slotted) - YES */
      color: khaki;
    }
    
    slot[name=slot2] + .siblingC { /* slot2 sibling - YES */
      color: blue;
    }
    
  </style>
  <div>
    <slot name="slot1"></slot>
    <div class="siblingA">Sibling A of Slot 1</div>
    <div class="siblingB">Sibling B of Slot 1</div>
  </div>
  <hr/>
  <div>
    <slot name="slot2"></slot>
    <div class="siblingC">Sibling C of Slot 2</div>
  </div>
</template>

<div class='templateMe'>
  <span slot="slot1">Im in Solt 1</span>
  <span slot="slot2" class="selectMeA">
    Im in Solt 2, im selectable.
    <div class='selectMeB'>
      NOT selectable (because no top level node of slotted)!
    </div>
  </span>
  <span slot="slot2" class="selectMeC" name="myName">Im in Solt 2 too and selectable!</span>
</div>

更多信息在这里

插槽元素(来自于光影DOM),::slotted(selector) 允许选择插槽元素本身,但不能选择它们的子元素。


2
感谢您详细的回答。在您的示例中,我正在寻找的是:slot[name=slot2]::slotted(.selectMeA + .selectMeC),如果我理解正确,这是不可能的,尽管两者都是顶级子元素。 - spbks
这是正确的,因为您正在使用组合符号 + - SirPilan
4
我尝试了 ::slotted(.selectMeA) + ::slotted(.selectMeC),但这也没有起作用。::slotted 似乎是终点。 - SirPilan
2
有人知道这是出于什么原因进行的吗?还是组合器将来可能会起作用,但现在还没有?我想要它们。 - wesruv

6

插槽中放置的DOM应该由拥有该DOM的CSS控制,而不是由自定义元素控制。

Web组件允许对放置在插槽中的DOM进行极小的CSS控制。基本上只有顶层元素(以及被子节点自动继承的东西)。

这是一个有意识的决定,可能永远不会改变。


谢谢,我也已经阅读了有关不允许在::slotted中使用复杂选择器与性能有关的决定,因此我希望有一种方法可以针对插槽内的同级元素进行选择,因为它们是顶级元素。 - spbks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接