【问题标题】:Get all elements in selection/highlight using window.getSelection使用 window.getSelection 获取选择/突出显示的所有元素
【发布时间】:2018-04-16 22:39:46
【问题描述】:
我可以获取单个元素或共同的祖先元素,但我不知道如何获取所有突出显示的元素。
这是一个获取共同祖先的演示。
console.clear();
document.querySelector('div').addEventListener('mouseup', () => {
const selection = window.getSelection();
const elem = selection.getRangeAt(0).commonAncestorContainer.parentNode;
console.log(elem);
});
<div contenteditable="true">
<header>
<h1>Rich Text Editing Development</h1>
<p>I'm <strong><em>really</em> annoyed</strong> with trying to figure out this answer.</p>
</header>
</div>
由于rangeCount 始终只有 1,并且我从 selection 和其他子项中看到的对象没有所选项目的数组或 nodeList(我注意到),我不知道该怎么办。
那么我如何知道哪些元素被选中/突出显示?
【问题讨论】:
标签:
javascript
wysiwyg
contenteditable
rich-text-editor
【解决方案1】:
虽然您将获得后代元素的副本而不是对真实元素的引用,但您可以使用 Range 的 cloneContents() 方法,除了共同的祖先父节点(如果使用 ES5,IE11 甚至支持语法):
document.addEventListener('mouseup', () => {
console.clear();
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
console.log('Selected elements:');
range.cloneContents().querySelectorAll('*').forEach(e => console.log(e));
console.log('Selected text/elements parent:');
console.log(range.commonAncestorContainer.parentNode);
});
<div contenteditable="true">
<header>
<h1>Rich Text Editing Development</h1>
<p>I'm <strong><em>really</em> annoyed</strong> with trying to figure out this answer.</p>
</header>
</div>