Polymer1.x:如何命令式(使用JS)获取自定义CSS属性的值?
Polymer 1.x: How to imperatively (using JS) obtain the value of a custom CSS property?
在下面的示例中,我有一个 parent 自定义元素调用 child 自定义元素。 child 有一个变量 color
CSS 属性 for p
可以在 parent CSS 中定义的元素。
在child元素的JS中,我想读取parent处选择的--custom-color
值。在本例中,值为 yellow
。换句话说:当 getCustomColor()
方法是 运行 时,我希望控制台日志显示为 "Your custom color is yellow."
我在getCustomColor()
方法中放入什么JavaScript来定义var yourColor
?
my-parent-element.html
<style>
my-child-element {
--custom-color: yellow;
}
</style>
<template>
<my-child-element></my-child-element>
</template>
my-child-element.html
<style>
p {
color: var(--custom-color);
}
</style>
<script>
getCustomColor: function() {
var yourColor = // What goes here to obtain the correct value of 'yellow'?
console.log('Your custom color is' + yourColor);
}
</script>
仅供参考:This documentation describes the custom style API。但是我似乎找不到我在这个问题中描述的内容的参考。
您链接的文档实际上提到了它...
您只需要检查 this.customStyle['--my-property-name']
,它将具有 属性
的值
根据@BryanDowning 的评论:
var s = document.querySelector('p');
var yourColor = window.getComputedStyle(s).getPropertyValue('color');
// Using Polymer syntax, the above line could be written as follows:
var yourColor = s.getComputedStyleValue('color');
那种作品。它 returns 第一个 p
元素的 color
属性 的当前值。
在下面的示例中,我有一个 parent 自定义元素调用 child 自定义元素。 child 有一个变量 color
CSS 属性 for p
可以在 parent CSS 中定义的元素。
在child元素的JS中,我想读取parent处选择的--custom-color
值。在本例中,值为 yellow
。换句话说:当 getCustomColor()
方法是 运行 时,我希望控制台日志显示为 "Your custom color is yellow."
我在getCustomColor()
方法中放入什么JavaScript来定义var yourColor
?
<style>
my-child-element {
--custom-color: yellow;
}
</style>
<template>
<my-child-element></my-child-element>
</template>
my-child-element.html
<style>
p {
color: var(--custom-color);
}
</style>
<script>
getCustomColor: function() {
var yourColor = // What goes here to obtain the correct value of 'yellow'?
console.log('Your custom color is' + yourColor);
}
</script>
仅供参考:This documentation describes the custom style API。但是我似乎找不到我在这个问题中描述的内容的参考。
您链接的文档实际上提到了它...
您只需要检查 this.customStyle['--my-property-name']
,它将具有 属性
根据@BryanDowning 的评论:
var s = document.querySelector('p');
var yourColor = window.getComputedStyle(s).getPropertyValue('color');
// Using Polymer syntax, the above line could be written as follows:
var yourColor = s.getComputedStyleValue('color');
那种作品。它 returns 第一个 p
元素的 color
属性 的当前值。