Polymer 元素中的 getElementById

getElementById in Polymer element

如何在 Polymer 自定义元素中使用 getElementById?

这是我的元素:

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../styles/shared-styles.html">

<dom-module id="bb-calendar">

  <template>

    <style is="custom-style" include="shared-styles"></style>

    <div class="card">
            <paper-toolbar>
                <div title>Calendar</div>
            </paper-toolbar>
            <div id="hideme">
                <div>this should be hidden</div>
            </div>
    </div>

  </template>

  <script>

    Polymer({

      is: 'bb-calendar',

      ready: function() {
        document.getElementById("hideme").style.display = 'none';
      }

    });

  </script>

</dom-module>

当我 运行 代码时,我收到此错误消息:Uncaught TypeError: Cannot read property 'style' of null

显然我做错了什么,但我不知道是什么。

我会用

ready: function() {
  this.$.hideme.style.display = 'none';
}

of 当元素在 <template dom-if...><template dom-repeat...>

内时
ready: function() {
  this.$$('#hideme').style.display = 'none';
}   

最后,我将使用 class 绑定并将 class 绑定到元素并更新 属性 以反映该更改并使用 CSS 来设置 style.display

<template>
  <style>
    .hidden { display:none; }    
  </style>
   ...
  <div class$="{{hiddenClass}}">
    <div>this should be hidden</div>
  </div>
Polymer({

  is: 'bb-calendar',

  properties: {
      hiddenClass: String,
  },

  ready: function() {
    this.hiddenClass = 'hidden';
  }

});

您的问题实际上是当触发就绪回调时您的元素未附加到文档 DOM。对于简单的 showing/hiding 元素,您可以像这样使用隐藏属性:<div hidden$="{{!shouldShow}}">