我为我们的站点编写的内容管理系统使用书签来发布文章,它使用 document.getSelection() 读取页面上的选定区域。但在某些情况下,阅读所选区域的底层 HTML 代码、获取链接和其他 HTML 格式也非常有用。
有人知道 jQuery 插件或其他 Javascript 技术可以访问生成选定区域的原始 HTML 吗?
最佳答案
首先,如您所说,获取 selection
var sel = document.getSelection();
这也有一些关于选定节点的详细信息,但如果您想做更多,请将其转换为 range (如果 .rangeCount > 1
你可能想在这里循环)
var range = sel.getRangeAt(0);
接下来,使用 range.commonAncestorContainer
和 range.startContainer
遍历 DOM 树,执行您想要的任何操作,直到到达 range.endContainer
。
所有这些节点都应该在选择中。
这里有一些代码将返回所有(顶级)选定节点,并且可以选择将回调应用到选定的每个节点。
function selectedNodes(callback, context) {
var sel = document.getSelection(),
range = sel.getRangeAt(0),
indices = [],
nextNode = function nextNode(e) {
if (e.childNodes.length > 0) return e.childNodes[0];
while(!e.nextSibling && e.parentNode) e = e.parentNode;
return e.nextSibling;
},
e = range.startContainer;
if (callback) {
callback.call(context, e);
while(e !== range.endContainer) {
e = nextNode(e);
callback.call(context, e);
}
e = range.startContainer;
}
if (e === range.commonAncestorContainer) return [e];
else {
while (e !== range.commonAncestorContainer) {
indices[0] = Array.prototype.indexOf.call(e.parentNode.childNodes, e);
e = e.parentNode;
}
e = range.endContainer;
while (e !== range.commonAncestorContainer) {
indices[1] = Array.prototype.indexOf.call(e.parentNode.childNodes, e);
e = e.parentNode;
}
return Array.prototype.slice.call(e.childNodes, indices[0], indices[1]+1);
}
}
/*
selectedNodes(console.log, console);
node1
..
nodeN
[node1, .., nodeM] // only top-level
*/
关于javascript - 有没有办法获取选定区域的底层HTML代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665776/