有没有办法获取所选区域的基础HTML代码?

时间:2012-12-02 02:11:15

标签: javascript jquery

我为网站编写的内容管理系统使用书签来发布文章,文章使用document.getSelection()读取页面上的选定区域。但在某些情况下,阅读所选区域的基础HTML代码,获取链接和其他HTML格式也非常有用。

有人知道jQuery插件或其他Javascript技术来访问生成所选区域的原始HTML吗?

1 个答案:

答案 0 :(得分:3)

首先,如您所说,获取selection

var sel = document.getSelection();

这也包含有关所选节点的一些详细信息,但如果您想要执行更多操作,请将其转换为range(如果.rangeCount > 1,则可能需要在此循环)

var range = sel.getRangeAt(0);

接下来,使用range.commonAncestorContainerrange.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
*/
相关问题