如何获取包含当前选择的DOM元素? [英] How can I get the DOM element which contains the current selection?
本文介绍了如何获取包含当前选择的DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您可以使用鼠标选择网页的一部分。
我知道我可以获得当前选择的文本,但是如何获取包含当前选择开始或结束的DOM元素?
$ b $在IE中,使用document.selection.createRange()。parentElement()并在实际的浏览器中使用window.getSelection()。getRangeAt(0).startContainer .parentNode。这样的东西: 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;
}
}
You can select a part of a web page with the mouse.
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?
解决方案
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屋!
查看全文