以下是我所拥有的元素的缩减版本:
<dom-module id="my-element">
<template>
<style>
:host {
display: inline;
}
.dark {
background: black;
color: white;
}
</style>
<span id="container">
<content></content>
</span>
</template>
<script>
Polymer({
is: 'my-element',
ready: function () {
var containerEl = this.$.container;
var containerText = containerEl.textContent.trim();
// create element
var clippedSpan = document.createElement('span');
clippedSpan.textContent = containerText;
clippedSpan.classList.add("dark");
// clear container
containerEl.innerHTML = '';
containerEl.appendChild(clippedSpan);
// update the styles
(this.domHost || Polymer).updateStyles();
}
});
</script>
</dom-module>
通过将以下内容添加到index.html页面来使用:
<my-element>text goes here</my-element>
<script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="https://polygit.org/components/polymer/polymer.html">
<dom-module id="my-element">
<template>
<style>
:host {
display: inline;
}
.dark {
background: black;
color: white;
}
</style>
<span id="container">
<content></content>
</span>
</template>
<script>
Polymer({
is: 'my-element',
ready: function() {
var containerEl = this.$.container;
var containerText = containerEl.textContent.trim();
// create element
var clippedSpan = document.createElement('span');
clippedSpan.textContent = containerText;
clippedSpan.classList.add("dark");
// clear container
containerEl.innerHTML = '';
containerEl.appendChild(clippedSpan);
// update the styles
(this.domHost || Polymer).updateStyles();
}
});
</script>
</dom-module>
<my-element>text goes here</my-element>
我可以看到创建的span
元素确实应用了类dark
,但实际上并没有应用dark
类的任何样式。这必须是因为它是作为孩子动态添加的。我尝试在updateStyles
和全局this
对象上调用Polymer
函数无效。
如何确保正确应用样式?
使用<content>
标记而不是属性的原因纯粹是为了简单起见。
答案 0 :(得分:2)
Polymer provides a custom API for manipulating DOM such that local DOM and light DOM trees are properly maintained.
Note: All DOM manipulation must use this API, as opposed to DOM API directly on nodes.
Polymer.dom(containerEl).appendChild(clippedSpan);