在HTML文本编辑器中如何获得光标父节点对象?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>
鼠标光标位置所在节点
</title>
<script>
var isIE = navigator.userAgent.indexOf("MSIE")>0;
var Q_EDITFORM_DOCUMENT = null;
var Q_SELECTION = null;
var Q_RANGE = null;
var Q_RANGE_TEXT = "";
function getParentNode()
{
if(isIE)
{
return document.selection.createRange().parentElement();
}
else
{
var startRangeNode = Q_RANGE.startContainer;
if (startRangeNode.nodeType == 3)
{
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
}
else
{
if (startRangeNode.tagName.toLowerCase() == 'html')
{
startRangeNode = startRangeNode.childNodes[0].nextSibling;
}
}
return startRangeNode;
}
}
//插入div的相关处理函数
function QEditformDocument()
{
if (isIE)
{
Q_EDITFORM_DOCUMENT = document;
}
else
{
Q_EDITFORM_DOCUMENT = document;
}
}
function QSelection()
{
if (isIE)
{
Q_SELECTION = Q_EDITFORM_DOCUMENT.selection;
Q_RANGE = Q_SELECTION.createRange();
Q_RANGE_TEXT = Q_RANGE.text;
//alert(Q_RANGE_TEXT);
}
else
{
Q_SELECTION = Q_EDITFORM_DOCUMENT.getSelection();
Q_RANGE = Q_SELECTION.getRangeAt(0);
Q_RANGE_TEXT = Q_RANGE.toString();
//console.dir(Q_RANGE_TEXT);
}
}
function test(){
QEditformDocument();
QSelection();
var parentobj = getParentNode();
console.dir(parentobj);
}
</script>
</head>
<body>
<div contenteditable="true" onclick="test();">
<b>点我,我是b节点</b><br/>
<i>点我,我是i节点</i><br/>
<em>点我,我是em节点</em>
</div>
</body>
</html>