问题
I'm attempting to follow the Custom property API for Polymer elements docs with regards to updating an element's CSS properties (and styles) programmatically but can't seem to get it working. Here is my current attempt:
<link rel="import" href="https://rawgit.com/Polymer/polymer/master/polymer.html">
<dom-module id="my-namecard">
<style>
:host {
--color: green;
}
span {
color: var(--color, orange);
}
</style>
<template>
<div>
Hi! My name is <span>{{name}}</span>
</div>
<button on-click="redClick">Set text to Red</button>
<button on-click="blueClick">Set text to Blue</button>
</template>
<script>
Polymer({
is: 'my-namecard',
properties: {
name: {
type: String
}
},
redClick: function() {
console.log('Setting "--color" red');
this.customStyle['--color'] = 'red';
this.updateStyles();
},
blueClick: function() {
console.log('Setting "--color" blue');
this.customStyle['--color'] = 'blue';
this.updateStyles();
}
});
</script>
</dom-module>
<my-namecard name="Sean"></my-namecard>
I've also attempted not setting a CSS property and using a direct style such as:
redClick: function() {
console.log('Setting "color" red');
this.customStyle['color'] = 'red';
this.updateStyles();
}
I've created a codepen demonstrating the issue
回答1:
You've hit a bug in the current version of Polymer, where a style change like this will propagate to child Polymer elements, but not to the element itself. See:
https://github.com/Polymer/polymer/issues/1851
The workaround is to call Polymer.updateStyles()
instead of this.updateStyles()
.
Here's the updated codepen.
来源:https://stackoverflow.com/questions/30854101/change-style-programmatically