xul-获取选择 html
我有以下函数,应该为网页上用户选择的区域获取 HTML。 这个功能似乎不能正常工作。
有时,它会获取也未选择的 html。
有人可以研究一下这个功能吗? - 多谢。
//----------------------------------------获取选定的 HTML----------------- --------
函数 getSelectionHTML(){
if (window.getSelection)
{
var focusedWindow = document.commandDispatcher.focusedWindow;
var sel = focusedWindow.getSelection();
var html = "";
var r = sel.getRangeAt(0);
var parent_element = r.commonAncestorContainer;
var prev_html = parent_element.innerHTML;
if(prev_html != undefined)
{
return prev_html;
}
return sel;
}
return null;
}
I have the following function that is supposed to get HTMLs for the user selected area on the web page. This function does not seems to work properly.
Sometime, it gets htmls which is not selected also.
Can anyone please look into this function? -- Thanks a lot.
//----------------------------Get Selected HTML------------------------
function getSelectionHTML(){
if (window.getSelection)
{
var focusedWindow = document.commandDispatcher.focusedWindow;
var sel = focusedWindow.getSelection();
var html = "";
var r = sel.getRangeAt(0);
var parent_element = r.commonAncestorContainer;
var prev_html = parent_element.innerHTML;
if(prev_html != undefined)
{
return prev_html;
}
return sel;
}
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您正在获取父元素的内容而不是选择本身。 如果父元素包含除您选择的内容之外的任何内容,那么您也会得到它。
此行 返回 选择对象。 它包含用户选择的确切文本。 然后,您可以从选择中获取范围并获取 commonAncestorContainer。 因此,如果您有这样的代码:
并且您的用户从第一个句子的“s”到第二个句子的“s”进行选择,那么 commonAncestorContainer 就是
div
元素,因此您还会得到文本的其余部分。这样做的一个很好的理由是,如果您想保证自己有一个有效的 HTML 片段(这似乎是这种情况,由您的函数名称暗示),但如果您只想要选定的文本,则调用 toString 直接在范围上使用方法:
It looks to me like you're getting the contents of the parent element rather than the selection itself. If the parent element contains anything other than what you have selected, then you'll get that too.
This line returns a selection object. It contains the exact text selected by the user. You then get the range from the selection and get the commonAncestorContainer. So if you have code like this:
And your user selects from the 's' of the first sentence to the 's' of the second sentence then the commonAncestorContainer is the
div
element so you'll also get the rest of the text.A good reason for this would be if you wanted to guarantee yourself a valid HTML fragment (this seems to be the case, implied by your function name), but if you just want the selected text then call the toString method on the range directly: