【问题标题】:Polymer 1.x: How to imperatively (using JS) obtain the value of a custom CSS property?Polymer 1.x:如何强制(使用 JS)获取自定义 CSS 属性的值?
【发布时间】:2016-11-14 00:04:58
【问题描述】:

在以下示例中,我有一个父自定义元素调用子自定义元素。子元素有一个变量 color CSS 属性,用于 p 元素,可以在父 CSS 中定义。

在子元素的JS中,我想读取父元素选择的--custom-color值。在这种情况下,值为yellow。换句话说:当getCustomColor() 方法运行时,我希望控制台日志显示“您的自定义颜色是黄色”。

我在getCustomColor() 方法中放入什么JavaScript 来定义var yourColor?

我的父元素.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。但我似乎找不到对我在这个问题中描述的内容的参考。

【问题讨论】:

  • 您是否有在 css 中添加该自定义道具的约束?使用data- 属性并使用.data("custom-color") 读取它怎么样。如果这不是一个选项,您可以从元素中读取.css() 道具并搜索您的--custom-color 道具......如果您可以控制圆顶的渲染方式,我肯定会使用data 方法。顺便说一句,该建议仅基于 jquery 和 html 函数/元素。我以前没有使用过聚合物
  • 您链接的文档实际上提到了它...您只需要检查this.customStyle['--my-property-name'],它将具有该属性的值
  • 我将其作为答案,以便搜索此内容的人更容易找到它

标签: javascript css polymer polymer-1.0 custom-element


【解决方案1】:

您链接的文档实际上提到了它...

您只需要检查this.customStyle['--my-property-name'],它将具有该属性的值

【讨论】:

  • 也可以使用window.getComputedStyle($0).getPropertyValue('--custom-color'),其中$0 是对DOM 元素的引用。来自:stackoverflow.com/a/36609605/230167
  • 忍者两次。今天不是我的日子。你们两个都投赞成票。
  • 当我执行var yourColor = this.customStyle['--custom-color'] 时,我得到undefined。有什么想法吗?
  • @abluejelly:尽管我赞成并接受了这个答案,但我不得不redo this question here,因为我没有指定我想要一个工作示例,JSbin。因此,如果您想尝试,我很乐意为您提供支持和accept your answer to this quetstion。
【解决方案2】:

@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');

这样的作品。它返回第一个p 元素的color 属性的当前值。

【讨论】:

  • 另外,see this jsBin 是一个类似的工作示例。 ... jsbin.com/bavezaciwi/edit?html,输出
猜你喜欢
  • 1970-01-01
  • 2021-11-21
  • 2017-01-07
  • 2013-04-16
  • 2018-11-13
  • 1970-01-01
  • 2019-10-24
  • 2015-04-18
  • 1970-01-01
相关资源
最近更新 更多