如何用javascript选择html文本? [英] How to get selected html text with javascript?

查看:341
本文介绍了如何用javascript选择html文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can use the following code to get selected text:

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

但是如何获得所选的Html,其中包括text和html标签?

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

推荐答案

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

In IE <= 10 browsers, it's:

document.selection.createRange().htmlText

As @DarrenMB指出IE11不再支持这一点。请参阅此答案以供参考。

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

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

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).

这篇关于如何用javascript选择html文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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