[英]How do I modify the value of a custom global style using Polymer?
例如,如果我写:
<style is="custom-style">
:root {
--p-color: red;
}
</style>
它会定义一个变量,我可以在我的范围内使用它:
<dom-module id="so-example">
<template>
<style>
:host p {
color: var(--p-color);
}
</style>
<p>this is a test</p>
</template>
<script>Polymer({ is: 'so-example' });</script>
</dom-module>
...
<so-example></so-example>
现在,假设我只想在so-example
的范围内更改样式。 我可以写:
var el = document.querySelector('so-example');
el.customStyle['--p-color'] = 'red';
el.updateStyles();
这将神奇地改变范围内所有段落的颜色。 但是之所以使用is="custom-style"
块,是因为--p-color
用于各种不同的元素。 现在,我无法使用上述方法更改其值。 如果这样做的话,它只会改变我所说的示波器的颜色。
在文档作用域中定义此变量后,是否可以修改该变量?
您可以使用Polymer.updateStyles({/* new styles */})
全局更新样式,而不是在每个元素上调用updateStyles()
。
Polymer.updateStyles({
'--p-color': 'blue'
});
HTMLImports.whenReady(() => { Polymer({ is: 'x-foo' }); Polymer({ is: 'x-bar' }); }); function changeColor() { Polymer.updateStyles({ '--p-color': 'blue' }); }
<head> <base href="https://polygit.org/polymer+1.8.0/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> </head> <body> <style is="custom-style"> :root { --p-color: red; } </style> <x-foo></x-foo> <x-bar></x-bar> <button onclick="changeColor()">Change color</button> <dom-module id="x-foo"> <template> <style> p { color: var(--p-color); } </style> <p>x-foo</p> </template> </dom-module> <dom-module id="x-bar"> <template> <style> p { color: var(--p-color); } </style> <p>x-bar</p> </template> </dom-module> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.