如何使用javascript获取选定的html文本?

发布于 2024-11-01 02:27:53 字数 181 浏览 2 评论 0 原文

我可以使用以下代码来获取选定的文本:

text=window.getSelection(); /// 对于火狐浏览器 文本=document.selection.createRange().text; /// for IE

但是我怎样才能获得选定的Html,其中包括文本和html标签呢?

I can use the following code to get selected text:

text=window.getSelection(); /// for Firefox
text=document.selection.createRange().text; /// for IE

But how can I get the selected Html, which includes the text and html tags?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

坏尐絯℡ 2024-11-08 02:27:53

这里有一个函数,可以让你获得与所有主要浏览器中当前选择相对应的 HTML。它还可以处理选择中的多个范围(目前仅在 Firefox 中实现):

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

alert(getSelectionHtml());

Here's a function that will get you HTML corresponding to the current selection in all major browsers. It also handles multiple ranges within a selection (currently only implemented in Firefox):

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

alert(getSelectionHtml());
毁梦 2024-11-08 02:27:53

在 IE <= 10 浏览器中,它是:

document.selection.createRange().htmlText

正如 @DarrenMB 指出的那样,IE11 不再支持这一点。请参阅此答案以供参考。


在非 IE 浏览器中,我只是尝试使用这个...这似乎有效,会将节点分成两半并创建额外的跨度,从而产生副作用,但这是一个起点:

var range = window.getSelection().getRangeAt(0),
  content = range.extractContents(),
     span = document.createElement('SPAN');

span.appendChild(content);
var htmlContent = span.innerHTML;

range.insertNode(span);

alert(htmlContent);

不幸的是,我似乎无法将节点恢复原样(例如,因为您可以从跨度中拉出一半文本)。

In IE <= 10 browsers, it's:

document.selection.createRange().htmlText

As @DarrenMB pointed out IE11 no longer supports this. See this answer for reference.


In non-IE browsers, I just tried playing with this... this seems to work, WILL have side effects from breaking nodes in half and creating an extra span, but it's a starting point:

var range = window.getSelection().getRangeAt(0),
  content = range.extractContents(),
     span = document.createElement('SPAN');

span.appendChild(content);
var htmlContent = span.innerHTML;

range.insertNode(span);

alert(htmlContent);

Unfortunately, I can't seem to put the node back as it was (since you can be pulling half the text from a span, for instance).

如果没有你 2024-11-08 02:27:53

这就是我的想法。使用 IE、Chrome、Firefox、Safari、Opera 进行测试。不返回空字符串。

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}

Here's what I came up with. Tested with IE, Chrome, Firefox, Safari, Opera. Doesn't return empty string.

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}
如果没有 2024-11-08 02:27:53

@zyklus:

我修改了你的函数来工作(我使用的是 jQuery,但这些部分可以很容易地用 Javascript 重写):

function getSelectionHtml() {
    var htmlContent = ''

    // IE
    if ($.browser.msie) {
        htmlContent = document.selection.createRange().htmlText;
    } else {
        var range = window.getSelection().getRangeAt(0);
        var content = range.cloneContents();

        $('body').append('<span id="selection_html_placeholder"></span>');
        var placeholder = document.getElementById('selection_html_placeholder');

        placeholder.appendChild(content);

        htmlContent = placeholder.innerHTML;
        $('#selection_html_placeholder').remove();

    }


    return htmlContent;
}

@zyklus:

I modified your function to work (I'm using jQuery but those pieces can be easily rewritten in Javascript):

function getSelectionHtml() {
    var htmlContent = ''

    // IE
    if ($.browser.msie) {
        htmlContent = document.selection.createRange().htmlText;
    } else {
        var range = window.getSelection().getRangeAt(0);
        var content = range.cloneContents();

        $('body').append('<span id="selection_html_placeholder"></span>');
        var placeholder = document.getElementById('selection_html_placeholder');

        placeholder.appendChild(content);

        htmlContent = placeholder.innerHTML;
        $('#selection_html_placeholder').remove();

    }


    return htmlContent;
}
北城孤痞 2024-11-08 02:27:53

我发现 highlight 插件是最佳匹配,它非常轻,您可以使用它突出显示部分内容

$('li').highlight('bla');

I found highlight plugin to be the best match, it is very light and with it you can highlight part of the content:

$('li').highlight('bla');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文