8

我正在玩 Google 的 Polymer-Project Web-Components Library。我想构建一个包含画布元素的自定义标签,并通过 javascript 从自定义元素中访问它。但我无法使用 document.querySelector 或 document.getElementById 访问它 - 任何类似问题的提示或经验都值得赞赏。

这是我的来源:

<polymer-element name="sprite-canvas">
<template>
<style>
.leinwand {
 width:200px;
 height:200px;
 background-color: lightblue;
 }
 </style>
<canvas class="leinwand" width="200" height="200"></canvas>
</template>
<script>

Polymer('sprite-canvas', {
leinwand : null,
ready: function() {  
console.log(document.getElementsByTagName('canvas'));
console.log(document.querySelector('.leinwand'));
},
domReady: function() {
console.log(document.getElementsByTagName('canvas'));
console.log(document.querySelector('.leinwand'));
},
detached: function() { },
});
</script>    

console.log 输出总是返回一个 NULL / 空集合,不管我在生命周期的哪个部分尝试调用画布。我的错误在哪里,我做错了什么?

最好的问候,卢波

4

2 回答 2

11

document.getElementsByTagName('canvas')document.querySelector('.leinwand')在主文档中寻找节点。您想在元素的影子 dom 中查询:

<canvas id="c" class="leinwand" width="200" height="200"></canvas>

console.log(this.$.c);
console.log(this.shadowRoot.querySelector('.leinwand'));

我在第一个示例中使用了 Polymer 的自动节点查找功能。第二个展示了如何使用this.shadowRoot影子 dom 中的“范围”qS/qSA。

演示:http: //jsbin.com/bogorose/1/edit

于 2014-06-19T17:16:59.333 回答
2

这似乎自 2014 年以来发生了变化,对于我使用的聚合物 1.0

console.log(this.$$('.leinwand'));

更多看这里: https ://www.polymer-project.org/1.0/docs/devguide/local-dom

于 2016-07-20T06:30:02.310 回答