我有一个shared-styles
元素,可以保留我的大多数应用程序颜色。我可以在shared-styles.html
中手动更改颜色,如果我使用CSS变量,我的所有其他组件都可以从那里继承。
我的问题是我需要更新shared-styles.html
中的CSS变量,并让所有其他继承CSS变量的组件相应地更新它们的颜色。以下是我的shared-styles.html
。为简洁起见,我删除了除--app-primary-color
之外的所有变量。
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<!-- shared styles for all views -->
<dom-module id="shared-styles">
<template>
<style is="custom-style">
:host {
--app-primary-color:#2196F3;
}
</style>
</template>
<script>
class SharedStyles extends Polymer.Element {
static get is() { return 'shared-styles'; }
ready(){
super.ready();
console.log('update css');
this.updateStyles({'--app-primary-color': 'red'});
}
}
window.customElements.define(SharedStyles.is, SharedStyles);
</script>
</dom-module>
这就是我将它们包含在其他组件中的方式。例如:
<dom-module id="test-element">
<template>
<style include="shared-styles">
答案 0 :(得分:3)
共享样式不是Polymer元素,因此它不应扩展Polymer.Element
,也不应该有<script>
标记。它应该这样定义:
<强>共享styles.html 强>
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<!-- shared styles for all views -->
<dom-module id="shared-styles">
<template>
<style>
:host {
--app-primary-color: #2196F3;
}
</style>
</template>
</dom-module>
然后,在根元素(例如this.updateStyles
)中调用<my-app>
以在Polymer 2.0中应用全局样式。请注意,<my-app>
下的所有元素都将继承新指定的样式。
以下是使用Polymer CLI的polymer-2-starter-kit
模板的说明:
安装npm install polymer-cli@next
模板所需的前沿Polymer CLI(polymer-2-starter-kit
)。
执行命令
mkdir polymer-2-shared-styles-demo
cd polymer-2-shared-styles-demo
polymer init polymer-2-starter-kit
在src/my-app.html
中,在菜单中添加<button>
,这会更改--app-primary-color
的值:
<template>
<app-drawer-layout fullbleed>
<!-- Drawer content -->
<app-drawer id="drawer" slot="drawer">
<app-toolbar>Menu</app-toolbar>
<!-- **** LINE 77: Add button below **** -->
<button on-click="_changeAppColor">Change app color</button>
<script>
class MyApp extends Polymer.Element {
/* *** LINE 130: Define button-click handler below **** */
_changeAppColor() {
this.updateStyles({'--app-primary-color': 'red'});
}
在src/shared-styles.html
中,将.circle
的{{1}}更改为使用background
:
--app-primary-color
运行.circle {
/* *** LINE 33: Use --app-primary-color below **** */
background: var(--app-primary-color, #ddd);
以在默认浏览器中打开入门套件。