【问题标题】:how to select shadow-root elements如何选择阴影根元素
【发布时间】:2018-04-26 13:56:10
【问题描述】:

使用聚合物,我在通过标签名称选择元素时遇到问题。

<canvas id="chart" width="150" height="150"></canvas>

.

..

...

_drawChart(price, time) { var ctx = this.$.canvas.getContext('2d'); //error happened here

.

..

...

}

现在this.$.canvas.getContext('2d'); 在控制台中返回错误Uncaught TypeError: Cannot read property 'canvas' of undefined.

我通过 getElementById 从控制台手动选择元素,它返回 null,注意画布位于 shadow-root 树中。

【问题讨论】:

    标签: polymer web-component shadow-dom


    【解决方案1】:

    尝试this.$.chart.getContext('2d'); 而不是this.$.canvas.getContext('2d');

    【讨论】:

    • 就是这样,你能给我一个关键字来阅读更多关于聚合物如何访问dom节点的信息
    • 自动节点查找:Polymer 自动在其本地 DOM 中构建静态创建的实例节点的映射,以方便访问常用节点,而无需手动查询。在元素模板中指定的任何具有 id 的节点都按 id 存储在 this.$ 散列中。 polymer-project.org/1.0/docs/devguide/local-dom
    【解决方案2】:

    this.shadowRoot.getElementById("chart").getContext('2d'); 也可以。
    更长一点,但更本地化。

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2022-08-19
      • 2022-08-12
      • 1970-01-01
      相关资源
      最近更新 更多