可以使用 Javascript 获取用户用鼠标选择的任何内容,如下所示:http://www.motyar.info/2010/02/get-user-selected-text-with-jquery-and.html
我的问题是我不仅需要这段文字,而且还需要:
获取此文本周围的 html(例如,如果用户选择“hello”并且此 hello 在生成的源代码中为:“
<div><span>hello</span></div>
”,这就是它应该返回的内容)。对图形执行相同的操作
任何人都可以指导我完成此过程吗?或者如果不可能的话还有其他选择吗?
最佳答案
这将在所有主要浏览器中执行此操作。 IE 和更多符合标准的浏览器有单独的分支。在 IE 中,这稍微容易一些,因为从选择创建的专有 TextRange
对象具有一个方便的 htmlText
属性。在其他浏览器中,您必须使用 DOM Range 的 cloneContents()
方法创建一个包含所选内容副本的 DocumentFragment
,并通过附加以下内容从中获取 HTML片段到元素并返回元素的 innerHTML
属性。
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());
关于Javascript:获取围绕用户选择的html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3873779/