这个问题对我来说非常重要。
我有这个元素:
<div class="title">
Hello Every thig is<span style="font-family: Tahoma;font-size: 20px">Good ! </span>
</div>
如何获取所选文本的开始位置和结束位置?
这是我的代码。它在父元素没有任何子元素时有效。
var selectedRange = window.getSelection().getRangeAt(0);
var selectedNode = selectedRange.commonAncestorContainer;
console.log("selected node: ", selectedNode);
console.log(selectedRange.anchorNode)
console.log("selected node value: ", selectedNode.nodeValue);
console.log("selection chars range: START POS: ", selectedRange.startOffset);
console.log("selection chars range: END POS: ", selectedRange.endOffset);
&#13;
感谢您的帮助。
答案 0 :(得分:1)
var selection = function () {
var selectedRange = window.getSelection().getRangeAt(0);
if(selectedRange)
{
var sc = selectedRange.startContainer,
so = selectedRange.startOffset,
ec = selectedRange.endContainer,
eo = selectedRange.endOffset;
var editable = document.getElementById('editor');
var start = rootOffset(editable, { node: sc, offset: so });
var end = rootOffset(editable, { node: ec, offset: eo });
console.log(start.offset);
console.log(end.offset);
}
};
var rootOffset = function (root, point) {
if (point.node === root)
{
return point;
}
var previousSibling = point.node.previousSibling;
if (previousSibling) {
return {
node: point.node,
offset: rootOffset(root, {
node: previousSibling,
offset: nodeLength(previousSibling)
}).offset + point.offset
};
}
else
{
var parentNode = point.node.parentNode;
if(parentNode)
{
return rootOffset(root, { node: parentNode, offset: point.offset });
}
}
return point;
};
var isText = function (node) {
return node && node.nodeType === 3;
};
var nodeLength = function (node) {
if (isText(node)) {
return node.nodeValue.trim().length;
}
var length = 0;
var childNodes = node.childNodes;
if (childNodes)
{
for(var i = 0; i < childNodes.length; i++)
{
length += nodeLength(childNodes[i]);
}
}
return length;
};
<div id="editor" contenteditable="true">
<div class="title">Hello Every thig is<span style="font-family: Tahoma;font-size: 20px">Good ! </span>
</div>
</div>
<button type="button" id="btnLog" onclick="selection();">Log Selection</button>