假设我有一个名为 <my-course>
的自定义 Web 元素在 <style>
中定义了自己的样式定义中的标记,我根本不想更改此元素的文件,因为它是我元素的外部依赖项。
这<my-course>
元素有一个 <div>
<template>
中定义的 child 标签。
例子:
<dom-module id="my-course">
<template>
<style>
::host {
padding: 5px;
background: rgba(0,0,0,.2);
}
div#progress {
height: 20px;
width: 100%;
background: red;
}
</style>
<h1>This is my custom course element</h1>
<div id="progress"></div>
</template>
<script>
class MyCourse extends Polymer.Element {
static get is() {
return 'my-course';
}
}
window.customElements.define(MyCourse.is, MyCourse);
</script>
</dom-module>
我想用“background: green;”使 div#progress 变绿(默认情况下为红色)通过加载在同一页面中的外部样式表作为附加/使用自定义元素。
我尝试过:
my-course div#progress {
background: green;
}
但是不行,进度div一直是红色。似乎没有办法从元素本身外部设置 shadow dom 的样式,我已经尝试过 my-course::content div#progress,但没有结果(/deep/和::shadow 已被弃用)我以前实现过这个使用::shadow。
有人可以帮忙吗?谢谢
最佳答案
您应该使用 CSS 变量,例如:
::host {
--progress-background: red;
padding: 5px;
background: rgba(0,0,0,.2);
}
div#progress {
height: 20px;
width: 100%;
background: var(--progress-background);
}
并覆盖它:
my-course {
--progress-background: green;
}
更多信息在这里:https://www.polymer-project.org/2.0/start/first-element/step-5
关于css - Polymer 2 从外部样式表为元素的子节点设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749429/