4

我得到用户选择的文本:

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);

var content = selectRange.cloneContents(); // DocumentFragment

我怎样才能得到textNode内容DocumentFragment

4

3 回答 3

3

利用textContent

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);
var content = selectRange.cloneContents(); // DocumentFragment
var text = content.textContent;
于 2013-11-10T02:35:29.113 回答
1

过滤fragment.childNodes以获取文本节点:

const selection = window.getSelection();
const selectRange = selection.getRangeAt(0);
const fragment = selectRange.cloneContents(); // DocumentFragment
// Get the child nodes and filter them to only include text nodes
const textNodes = Array.from(fragment.childNodes).filter(child => child.nodeName === "#text");
于 2020-03-20T02:33:29.133 回答
0

结合一些技巧,很容易从任何容器节点(在本例中为片段)中提取文本节点。问题的片段部分与提取部分无关。

获取容器的所有子项,使用扩展运算符将它们转换为“真实”数组,...以便filter习惯。也可以跳过这部分,因为 HTMLCollection 确实支持forEach,因此可以在其中填充一个空数组。

请注意,这是Node.TEXT_NODE一个 DOM常量3

// create a demo fragment with some HTML mix of text nodes & elements
var frag = document.createRange().createContextualFragment("<a>1</a> 2 <b>3</b> 4.");

// now the work begins: get only the text nodes from the fragment
var textNodes = [...frag.childNodes].filter(node => node.nodeType == Node.TEXT_NODE)

// print the text nodes as an array
console.log( textNodes.map(node => node.textContent) )

于 2020-09-20T14:51:23.877 回答