Selecting slot text in Custom Element Shadow DOM

匆匆过客 提交于 2020-05-27 05:21:45

问题


I made a simple copy-paste component with regular html/css/js. I've tried to turn it into a web component and can no longer get the copy-paste behaviour to work.

The markup inside the shadow DOM is basically

<span contenteditable="true">
  <slot></slot>
</span>
<button>Copy</button>

The Javascript:

class CopyPaste extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.appendChild(copyPasteTemplate.content.cloneNode(true));
  }

  connectedCallback() {
    let copyButton = this.shadowRoot.querySelector('button');
    let textToCopy = this.shadowRoot.querySelector('span');

    function selectElementContents(el) {
      var range = document.createRange();
      range.selectNodeContents(el);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    }

    function copyText() {
      selectElementContents(textToCopy);
      document.execCommand('copy');
    }

    copyButton.addEventListener('click', copyText);
    textToCopy.addEventListener('click', copyText);
  }
}

window.customElements.define('copy-paste', CopyPaste);

回答1:


In your example, the textToCopy variable refers to the <slot> element, with no text inside.

If you want to get the ditributed node form the light DOM, of the <copy-paste> element, you should use the assignedNodes() method of the <slot> element:

let textToCopy = this.shadowRoot.querySelector('slot').assignedNodes()[0];

PS: note that the contenteditable attribute may not work as you expect in your given example.



来源:https://stackoverflow.com/questions/50311245/selecting-slot-text-in-custom-element-shadow-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!