css - shadow dom ::part 元素的样式子元素
问题描述
我有一个 web 组件,它在 shadow dom 中呈现以下内容:
<custom-banner>
#shadow-root
<div part="headertext">
I am the header text!
</div>
...
</custom-banner>
要设置 的样式headertext
,以下 css 效果很好:
custom-banner::part(headertext) {
border: 5px solid green;
}
现在说我有这样的事情:
<custom-banner>
#shadow-root
<div part="headertext">
I am the header text!
<span>I am the subheader text!</span>
</div>
...
</custom-banner>
有没有办法针对阴影部分的孩子?也就是说,像这样的东西(似乎不起作用):
custom-banner::part(headertext) span {
border: 5px solid red;
}
我意识到这种事情可能会削弱 的整个目的::part
,但也许不会?
需要明确的是,在此示例中,子标题跨度不是开槽子。它始终是组件的一部分,并且位于shadow dom 中。上面的示例是在浏览器中呈现的组件。
谢谢!
解决方案
唉,你只能设置节点本身的样式。::part
不是孩子,这会破坏::part
目的,
还不如允许所有来自外部的 shadowDOM 样式。(做不到)
如果您不想指定 a part="subheader"
,则
可以使用 CSS 属性,范围为part,请参阅--subheader: blue
好博客:
- 为什么我的 shadowDOM 继承样式
::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>
推荐阅读
- ios - 为什么 Xcode Storyboard 中所做的更改没有反映在模拟器/设备上?
- python - For 循环 if 语句在第一行返回不想要的结果
- javascript - @Input 和 @Output 在 Angular 5 中始终未定义
- .htaccess - 仅当存在查询字符串时,htaccess 才会重定向到新域
- sql - 如何根据另一个表列的条件自动更新列的值?
- mysql - 如何减少显示输出所需的加载时间?
- java - “现在更新”,Oracle,springframework,QuerySyntaxException
- r - r 带有 for 循环的闪亮反应数据
- symfony - 我无法显示我的 pagelist.html.twig(您可以忽略法语单词)
- mongodb - Mongo 查找查询不适用于某些值。