分配给innerHTML时,无法将样式应用于锚标记

时间:2016-06-13 23:59:31

标签: polymer polymer-1.0

我正在为元素的innerHTML分配一个包含锚标记的字符串。我需要设计这些,但是,我不知道该怎么做。以下是此StackOverflow post建议使用Polymer.domupdateStyles的示例:

Polymer({
  is: 'x-foo',
  properties: {
    value: {
      type: String,
      value: '<a href="//google.com">Hello</a>',
      observer: 'setValue'
    }
  },
  
  setValue: function() {
    Polymer.dom(this).innerHTML = this.value;
    this.updateStyles();
  }
});
<base href="https://polygit.org/polymer+:1.4.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">


<dom-module id="x-foo">
  <style>
    a {
      color: red;
    }
  </style>
  <template>
    <content></content>
  </template>
</dom-module>

<x-foo></x-foo>

这里是jsfiddle的链接: https://jsfiddle.net/cbelden/xamfhe52/

1 个答案:

答案 0 :(得分:1)

您无需致电updateStyles()。您的dom-module样式应该使用::content来定位分布式节点:

<style>
  ::content a {
    color: red;
  }
</style>

HTMLImports.whenReady(function() {

  Polymer({
    is: 'x-foo',
    properties: {
      value: {
        type: String,
        value: '<a href="//google.com">Hello</a>',
        observer: 'setValue'
      }
    },

    setValue: function() {
      Polymer.dom(this).innerHTML = this.value;
      //this.updateStyles(); // not needed
    }
  });

});
<base href="https://polygit.org/polymer+:1.4.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">


<dom-module id="x-foo">
  <style>
    ::content a {
      color: red;
    }
  </style>
  <template>
    <content></content>
  </template>
</dom-module>

<x-foo></x-foo>