如何使用javascript获取选定的html文本?
我可以使用以下代码来获取选定的文本:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有一个函数,可以让你获得与所有主要浏览器中当前选择相对应的 HTML。它还可以处理选择中的多个范围(目前仅在 Firefox 中实现):
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):
在 IE <= 10 浏览器中,它是:
正如 @DarrenMB 指出的那样,IE11 不再支持这一点。请参阅此答案以供参考。
在非 IE 浏览器中,我只是尝试使用这个...这似乎有效,会将节点分成两半并创建额外的跨度,从而产生副作用,但这是一个起点:
不幸的是,我似乎无法将节点恢复原样(例如,因为您可以从跨度中拉出一半文本)。
In IE <= 10 browsers, it's:
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:
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).
这就是我的想法。使用 IE、Chrome、Firefox、Safari、Opera 进行测试。不返回空字符串。
Here's what I came up with. Tested with IE, Chrome, Firefox, Safari, Opera. Doesn't return empty string.
@zyklus:
我修改了你的函数来工作(我使用的是 jQuery,但这些部分可以很容易地用 Javascript 重写):
@zyklus:
I modified your function to work (I'm using jQuery but those pieces can be easily rewritten in Javascript):
我发现 highlight 插件是最佳匹配,它非常轻,您可以使用它突出显示部分内容:
I found highlight plugin to be the best match, it is very light and with it you can highlight part of the content: