如何按名称选择所有插槽?

9

我正在处理这种情况...

<template>
  <slot name="thing"></slot>
  <slot name="other"></slot>
</template>

以及像这样的实现:

<custom-element>
  <div slot="thing"> Thing 1 </div>
  <div slot="thing"> Thing 2 </div>
  <div slot="other"> Thing 3 </div>
</custom-element>

我该如何使用CSS查询来同时影响Thing 1和Thing 2,但排除Thing 3?


1
属性选择器 [slot="thing"]{ border: 2px dashed #f00; } - admcfajn
在 Shadow DOM 中,:head[slot="thing"] 会是什么样子? - Jackie
1
我不确定关于 web-component 的实现... 我以为你只是在寻找 css 选择器... slot[name="thing"] 可能吗? - admcfajn
1
我发现在Web组件中尝试以下内容非常有用:在外部CSS中使用:defined[slot=...],在组件内部的CSS中使用:host::slotted()slot[name=...] - Sheraff
抱歉,我的意思是主机。 - Jackie
2个回答

7
在 Shadow DOM 的 <style> 标签中,您可以像 @admcfajn 在其第二个评论中建议的那样,直接将 CSS 样式应用于 <slot> 元素。
slot[name="thing"] { .. }

但是,如果您想在通过<slot>元素插入影子DOM时定位来自亮DOM的元素,应该使用::slotted()伪元素函数。

::slotted( div[slot="thing"] ) { color: green }

将具有属性slot="name"<div>中的文本标记为红色。

重要提示:第二种解决方案更好,因为来自轻DOM的CSS具有优先级。因此从轻DOM继承的样式将覆盖从插槽元素中继承的样式。请参见下面的background-color示例:

customElements.define( 'custom-element', class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow( { mode: 'open' } ).innerHTML = tpl.innerHTML
  }
} )
body { background-color: lightblue }
<template id=tpl>
  <style>
    ::slotted( [slot=thing] ) { background-color: green }
    slot[name="other"] { background-color: red }
  </style>
  <slot name="thing"></slot>
  <slot name="other"></slot>
</template>

<custom-element>
  <div slot="thing"> <div>Thing 1 </div></div>
  <div slot="thing"> Thing 2 </div>
  <div slot="other"> Thing 3 </div>
</custom-element>


0

对Supersharp答案的补充:

您可以使用全局CSS样式来设置插槽内容

div元素(在lightDOM中)带有slot属性,是主DOM的一部分

应用于这些元素的全局样式在插入shadowDOM时保持应用

customElements.define( 'custom-element', class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow( { mode: 'open' } )
        .innerHTML=`<slot name="thing"></slot>`
                  +`<slot name="other"></slot>`
                  +`<slot></slot>`
  }})
[slot] { background-color: lightblue }
<style id=GlobalStyle>
  [slot]:not([slot="other"]){
    background:green;
  }
</style>

<button onclick=GlobalStyle.disabled=!GlobalStyle.disabled>
TOGGLE GlobalStyle
</button>

<custom-element>
  <div slot="thing"> Thing 1 </div>
  <HR>
  <div slot="thing"> Thing 2 </div>
  <div slot="other"> Thing 3 </div>
  <div slot="none" > Thing 4 </div>
  <b>
    <div> Thing 5 </div>
  </b>
  <div slot="thing"> Thing 6 </div>
</custom-element>

注释

  • Thing 6Thing 3 之前插槽,因为插槽 thing 在插槽 other 之前定义。
  • Thing 4 在 lightDOM 中但没有被插槽,因为它没有匹配的插槽名称。
  • 所有其他 lightDOM 内容(特别是注意 HR)都被注入到未命名的插槽中。

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