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

℡╲_俬逩灬. 提交于 2019-12-11 06:16:45

问题


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.

In the JS of the child element, I want to read the --custom-color value selected at the parent. In this case, the value is yellow. Put another way: when the getCustomColor() method is run, I want the console log to read "Your custom color is yellow."

What JavaScript do I put in the getCustomColor() method to define 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>

FYI: This documentation describes the custom style API. But I can't seem to find the reference to what I'm describing in this question.


回答1:


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




回答2:


Per comment by @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.



来源:https://stackoverflow.com/questions/38317155/polymer-1-x-how-to-imperatively-using-js-obtain-the-value-of-a-custom-css-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!