0

我正在构建一个使用该<textarea>元素的 Web 组件,但我无法弄清楚如何让它像本机<textarea>元素一样接受内部文本。

<body>
  <textarea>this works</textarea>
  <expanding-textarea>this doesn't</expanding-textarea>
  <script type="module">
    const template = document.createElement("template");
    template.innerHTML = `<textarea></textarea>`;

    class ExpandingTextarea extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({ mode: "open" });
        this.shadowRoot.appendChild(template.content.cloneNode(true));
      }
    }
    customElements.define("expanding-textarea", ExpandingTextarea);
  </script>
</body>
4

2 回答 2

1

您需要在构造函数中设置新创建的 textarea 的 textContent 属性。我为你做了一个简化版。

class ExpandingTextarea extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    var textarea = document.createElement("textarea");
    textarea.textContent = this.textContent;
    this.shadowRoot.appendChild(textarea);
  }
}
customElements.define("expanding-textarea", ExpandingTextarea);
于 2019-12-23T13:34:21.843 回答
1

There are 2 types of Custom Elements

  • Autonomous Custom Elements (extend from (root) HTMLElement, like the first answer)
  • Customized Buil-In Elements (extend from existing elements)

So you can extend from HTMLTextAreaElement and get all functionality for free:

  class MyTextArea extends HTMLTextAreaElement {
    constructor() {
      super();
      this.placeholder = 'Type some text';
      this.cols = 60;
      this.rows = 10;
    }
  }

  customElements.define('my-textarea', MyTextArea, { extends: 'textarea' });
<textarea is=my-textarea></textarea>

Important Notes:

  • Opera & Safari do not support Customized Built-In Elements yet, there is a polyfill
  • Customized Built-In Textarea (because of its inner workings) can not have a shadowDOM
    most other Customized Built-In Elements can have a shadowDOM
  • You dynamically create a Customized Built-In Element with:
    document.createElement( "textarea", {is:"my-textarea"} )
  • Firefox incorrectly!! allows <my-textarea></my-textarea> notation, when defining elements late
于 2019-12-24T10:03:15.613 回答