gpt4 book ai didi

javascript - 使用 window.getSelection 获取选择/突出显示中的所有元素

转载 作者:行者123 更新时间:2023-11-30 14:39:39 26 4
gpt4 key购买 nike

我可以获取单个元素或公共(public)祖先元素,但我不知道如何获取所有被突出显示的元素。

这里有一个获取共同祖先的demo。

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,而且我从选择和其他子项中看到的对象没有所选项目的数组或节点列表(我注意到),我不知道是什么做。

那么我怎么知道哪些元素被选中/突出显示了呢?

最佳答案

虽然您将获得后代元素的副本而不是对真实元素的引用,但除了公共(public)祖先父节点 (如果使用 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>

关于javascript - 使用 window.getSelection 获取选择/突出显示中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49867273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com