如何获取包含当前选择的 DOM 元素? [英] How can I get the DOM element which contains the current selection?
本文介绍了如何获取包含当前选择的 DOM 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您可以用鼠标选择网页的一部分.
You can select a part of a web page with the mouse.
我知道我可以获取当前选择的文本但是我怎样才能获得获取包含当前选择的开始或结束的 DOM 元素?
I know that I can get the currently selected text but how can I get the DOM element which contains the start or end of the current selection?
推荐答案
在 IE 中,使用 document.selection.createRange().parentElement() 而在实际浏览器中使用 window.getSelection().getRangeAt(0).startContainer.父节点.像这样:
In IE, use document.selection.createRange().parentElement() and in real browsers use window.getSelection().getRangeAt(0).startContainer.parentNode. Something like this:
function getSelectedNode()
{
if (document.selection)
return document.selection.createRange().parentElement();
else
{
var selection = window.getSelection();
if (selection.rangeCount > 0)
return selection.getRangeAt(0).startContainer.parentNode;
}
}
这篇关于如何获取包含当前选择的 DOM 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文