使用 window.getSelection 获取 selection/highlight 中的所有元素
Get all elements in selection/highlight using window.getSelection
我可以获取单个元素或公共祖先元素,但我不知道如何获取所有被突出显示的元素。
这里有一个获取共同祖先的演示。
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,而且我从选择和其他子项中看到的对象没有所选项目的数组或节点列表(我注意到),我不知道该怎么做做。
那么我怎么知道哪些元素正在 selected/highlighted?
虽然您将获得后代元素的副本而不是对真实元素的引用,但除了公共祖先父节点(甚至支持IE11 如果使用 ES5 语法):
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>
我可以获取单个元素或公共祖先元素,但我不知道如何获取所有被突出显示的元素。
这里有一个获取共同祖先的演示。
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,而且我从选择和其他子项中看到的对象没有所选项目的数组或节点列表(我注意到),我不知道该怎么做做。
那么我怎么知道哪些元素正在 selected/highlighted?
虽然您将获得后代元素的副本而不是对真实元素的引用,但除了公共祖先父节点(甚至支持IE11 如果使用 ES5 语法):
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>