简体   繁体   English

Polymer 1.x:如何强制性地(使用JS)获得自定义CSS属性的值?

[英]Polymer 1.x: How to imperatively (using JS) obtain the value of a custom CSS property?

In the following example, I have a parent custom element calling a child custom element. 在下面的示例中,我有一个父自定义元素,它调用了一个子自定义元素。 The child has a variable color CSS property for p elements that can be defined in the parent CSS. 子级具有可在父级CSS中定义的p元素的可变color CSS属性。

In the JS of the child element, I want to read the --custom-color value selected at the parent. 在子元素的JS中,我想读取在--custom-color元素上选择的--custom-color值。 In this case, the value is yellow . 在这种情况下,该值为yellow Put another way: when the getCustomColor() method is run, I want the console log to read "Your custom color is yellow." 换句话说,当运行getCustomColor()方法时,我希望控制台日志显示为“您的自定义颜色为黄色”。

What JavaScript do I put in the getCustomColor() method to define var yourColor ? 我应该在getCustomColor()方法中使用什么JavaScript来定义var yourColor

my-parent-element.html my-parent-element.html
 <style> my-child-element { --custom-color: yellow; } </style> <template> <my-child-element></my-child-element> </template> 
my-child-element.html 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> 

FYI: This documentation describes the custom style API . 仅供参考: 本文档描述了自定义样式API But I can't seem to find the reference to what I'm describing in this question. 但是我似乎找不到对我在此问题中所描述内容的引用。

The docs you linked actually mention it... 您链接的文档实际上提到了它...

You just need to check this.customStyle['--my-property-name'] and it will have the value of the property 您只需要检查this.customStyle['--my-property-name'] ,它将具有该属性的值

Per comment by @BryanDowning: @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');

That sort of works. 那种作品。 It returns the current value of the color property of the first p element. 它返回第一个p元素的color属性的当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM