有没有办法获取选定区域的基础HTML代码? [英] Is there a way to get the underlying HTML code of a selected area?

查看:121
本文介绍了有没有办法获取选定区域的基础HTML代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The content management system I wrote for our site uses a bookmarklet to post articles, which reads the selected area on a page with document.getSelection(). But in some cases it would be very useful to read the underlying HTML code for the selected area as well, to get links and other HTML formatting.

是否有人知道使用jQuery插件或其他Java技术可以访问生成选定区域的原始HTML?

Anyone know of a jQuery plugin or other Javascript technique to access the raw HTML that produces a selected area?

推荐答案

首先,如您所说,获取选择

First, as you said, get the selection

var sel = document.getSelection();

这也确实包含有关选定节点的一些详细信息,但是如果您想做更多,则可以将其转换为

This does have some details about selected nodes, too, but if you want to do more then convert this to a range (If .rangeCount > 1 you may want to loop here)

var range = sel.getRangeAt(0);

接下来,使用range.commonAncestorContainerrange.startContainer遍历DOM树,执行您想要执行的任何操作,直到到达range.endContainer.
所有这些节点都应该在选择中.

Next, using range.commonAncestorContainer and range.startContainer walk through the DOM tree performing whatever you want until you reach range.endContainer.
All of these nodes should be in the selection.

这里有一些代码将返回所有(顶级)所选节点,并有选择地将回调应用于选择中的每个节点.

Here is some code that'll return all (top level) selected nodes and, optionally, apply a callback to every node in selection.

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
*/

这篇关于有没有办法获取选定区域的基础HTML代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆