cro*_*ill 7 css web-component shadow-dom
我有一个 Web 组件,可以在 Shadow dom 中呈现以下内容:
<custom-banner>
#shadow-root
<div part="headertext">
I am the header text!
</div>
...
</custom-banner>
Run Code Online (Sandbox Code Playgroud)
要设置 的样式headertext,以下 css 效果很好:
custom-banner::part(headertext) {
border: 5px solid green;
}
Run Code Online (Sandbox Code Playgroud)
现在说我有这样的东西:
<custom-banner>
#shadow-root
<div part="headertext">
I am the header text!
<span>I am the subheader text!</span>
</div>
...
</custom-banner>
Run Code Online (Sandbox Code Playgroud)
有没有办法针对阴影部分的孩子?也就是说,像这样的东西(这似乎不起作用):
custom-banner::part(headertext) span {
border: 5px solid red;
}
Run Code Online (Sandbox Code Playgroud)
我意识到这种事情可能会削弱 的整个目的::part,但也许不会?
需要明确的是,在此示例中,子标题范围不是带槽子项。它始终是组件的一部分,并且位于Shadow dom 中。上面的示例是在浏览器中渲染的组件。
谢谢!
唉,您只能设置Node::part 本身的样式。
不是孩子,这会达不到::part目的,
那么最好允许来自外部的所有ShadowDOM 样式。(无法完成)
exportparts属性可以将定义传递给part父节点
正如评论中提到的;您可以指定<span part="subheader">,
或者您可以使用 CSS 属性,范围仅限于部分,请参阅--subheader: blue
这完全取决于您想要向组件用户提供多少控制权以及哪种控制权。
好的博客:
::parts作者:Monica Dinculescu(谷歌):https ://meowni.ca/posts/part-theme-explainer/<style>
body {
/* note how 'inheritable styles' do style shadowDOM */
font: 28px Arial;
color: green;
}
custom-banner::part(headertext) {
/* style shadowDOM from global CSS */
background: pink;
--subheader: blue;
}
</style>
<custom-banner></custom-banner>
<script>
customElements.define("custom-banner", class extends HTMLElement {
constructor() {
super()
.attachShadow({mode:"open"})
.innerHTML = `<style> span { color:var(--subheader) } </style>` +
`<div part="headertext">I am the header text!` +
`<span>I am the subheader text!</span>` +
`</div>`;
}
});
</script>Run Code Online (Sandbox Code Playgroud)