前端组件化Polymer入门教程(7)——Local DOM

DOM元素的创建和管理被称为本地DOM(Local DOM)

本地DOM模板

如果你需要使用本地DOM,你们需要用<dom-module>并指定一个相匹配的ID

<dom-module id="x-foo">

  <template>I am x-foo!</template>

  <script>
    Polymer({
      is: 'x-foo'
    });
  </script>

</dom-module>

template里面写的css,html将不会影响外面的代码。有隔离的作用,他们称作Shadow DOM。脚本可以写在<dom-module>里面也可以写在外面。

通过this.$.name快速获取元素
<dom-module id="x-custom">

  <template>
    Hello World from <span id="name"></span>!
  </template>

  <script>

    Polymer({

      is: 'x-custom',

      ready: function() {
        this.$.name.textContent = this.tagName;
      }

    });

  </script>

</dom-module>

会获取到id为name的属性,这里是span

另外还可以通过this.$$(selector)来获取元素,$$返回第一个匹配的DOM,使用方法和document.querySelector一样。

通过content标签我们可以在外部插入内容
<x-custom>
    <p>这是文章的内容</p>
</x-custom>
<dom-module id="x-custom">
  <template>
    <header>这是头部</header>
    <section>
      <header>这是一篇文章的头部</header>
      <content></content>
    </section>
    <footer>这是底部</footer>
  </template>
  <script>
    Polymer({
      is: 'x-custom'
    });
  </script>
</dom-module>

原文地址:https://www.cnblogs.com/pssp/p/5925697.html