bit*_*ess 2 javascript wysiwyg contenteditable rich-text-editor
我可以获得单个元素或共同祖先元素,但我无法弄清楚如何获取所有突出显示的元素。
这是获取共同祖先的演示。
console.clear();
document.querySelector('div').addEventListener('mouseup', () => {
const selection = window.getSelection();
const elem = selection.getRangeAt(0).commonAncestorContainer.parentNode;
console.log(elem);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
由于rangeCount总是只有 1,并且我从选择和其他子项中看到的对象没有所选项目的数组或节点列表(我注意到),所以我不知道该怎么办。
那么我如何知道哪些元素被选择/突出显示?
尽管您将获得后代元素的副本而不是对真实元素的引用,但cloneContents()除了公共祖先父节点之外,您还可以使用 Range 的方法(如果使用 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);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2887 次 |
| 最近记录: |