使用javascript获取选定内容的原始HTML [英] Get the raw HTML of selected content using javascript

查看:94
本文介绍了使用javascript获取选定内容的原始HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Javascript在页面上获取所选内容的原始HTML?为了简单起见,我坚持支持 window.getSelection 的浏览器。



这里是一个例子; | 之间的内容代表我的选择。

 < p> 
< em> quick brown f | ox< / em>跳过懒惰的< strong> d< / strong> ;.
< / p>

我可以使用以下Javascript捕获并提醒规范化的HTML。

  var selectionRange = window.getSelection()。getRangeAt(0); 
selectionContents = selectionRange.cloneContents(),
fragmentContainer = document.createElement('div');
fragmentContainer.appendChild(selectionContents);
alert(fragmentContainer.innerHTML);

在上面的例子中,提示内容会折叠尾随元素并返回字符串< EM>牛< / EM>跳过懒< strong> d< / strong>



如何返回字符串 ox< / EM>跳过懒惰< strong> d< / code>

解决方案

HTML序列化程序。



selectionRange.startContainer / startOffset ,并从那里向前走树,直到你到达 endContainer / endOffset ,从节点输出HTML标记为你去,包括打开标签和属性,当你走进一个元素,并关闭标签时,当你去了 parentNode



没什么好玩的,尤其是如果你需要在某个时候支持完全不同的IE< 9 Range模型......

(注意你赢了不能完全获取原始HTML原始HTML,因为这些信息已经消失了,只有当前的DOM树被浏览器存储,这意味着像标签大小写,属性顺序,空白和省略隐式标签在源代码和您获得的代码之间会有所不同)


How would I get the raw HTML of the selected content on a page using Javascript? For the sake of simplicity, I'm sticking with browsers supporting window.getSelection.

Here is an example; the content between both | represent my selection.

<p>
    The <em>quick brown f|ox</em> jumps over the lazy <strong>d|og</strong>.
</p>

I can capture and alert the normalized HTML with the following Javascript.

var selectionRange = window.getSelection().getRangeAt(0);
    selectionContents = selectionRange.cloneContents(),
    fragmentContainer = document.createElement('div');
    fragmentContainer.appendChild(selectionContents);
alert(fragmentContainer.innerHTML);

In the above example, the alerted contents would collapse the trailing elements and return the string <em>ox</em> jumps over the lazy <strong>d</strong>.

How might I return the string ox</em> jumps over the lazy <strong>d?

解决方案

You would have to effectively write your own HTML serialiser.

Start at the selectionRange.startContainer/startOffset and walk the tree forwards from there until you get to endContainer/endOffset, outputting HTML markup from the nodes as you go, including open tags and attributes when you walk into an Element and close tags when you go up a parentNode.

Not much fun, especially if you are going to have to support the very different IE<9 Range model at some point...

(Note also that you won't be able to get the completely raw original HTML, because that information is gone. Only the current DOM tree is stored by the browser, and that means details like tag case, attribute order, whitespace, and omitted implicit tags will differ between the source and what you get out.)

这篇关于使用javascript获取选定内容的原始HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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