在自定义元素 Shadow DOM 中选择插槽文本 [英] Selecting slot text in Custom Element Shadow DOM
问题描述
我用普通的 html/css/js 制作了一个简单的复制粘贴组件.我试图把它变成一个 web 组件,但不能再让复制粘贴行为起作用.
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.
shadow DOM里面的标记基本上是
The markup inside the shadow DOM is basically
<span contenteditable="true">
<slot></slot>
</span>
<button>Copy</button>
Javascript:
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);
推荐答案
在您的示例中,textToCopy
变量指的是
元素,没有文本里面.
In your example, the textToCopy
variable refers to the <slot>
element, with no text inside.
如果您想从 <copy-paste>
元素的轻量 DOM 中获取分布式节点,您应该使用 assignedNodes()
的方法元素:
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:请注意,contenteditable
属性可能无法按您在给定示例中的预期工作.
PS: note that the contenteditable
attribute may not work as you expect in your given example.
这篇关于在自定义元素 Shadow DOM 中选择插槽文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!