我正在尝试找到选择的文本开头和结尾。
我的HTML结构是这样的:
<div id="viewer">
<iframe id="epubjs-iframe:eb39fd66-ffb7-48b2-add9-a2764fc0ad74" width="100%" height="100%" scrolling="no" style="border: medium none; visibility: visible;" s6745771569="true" replaced="true">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" style="overflow: hidden; width: 18825px; height: 496px; -moz-column-fill: auto; -moz-column-gap: 156px; -moz-column-width: 547px;">
<head>
`enter code here`<body style="margin: 0px; font-size: 100%;">
<p id="1_p_6" class="indent">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
</p>
</body>
</html>
</frame>
</div>
我正在使用这种JavaScript方法:
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
return caretOffset;
}
在我的情况下preCaretRange.selectNodeContents(element);
发出错误:
TypeError: Argument 1 of Range.selectNodeContents does not implement interface Node.
工作示例如下:
答案 0 :(得分:1)
这是正确的解决方案。
function getCaretCharacterOffsetWithin(objectId, win)
{
var startOffSet = 0;
var endOffset = 0;
var element = window.frames[0].document.getElementById(objectId);
var parentInnerHTML = element.innerHTML.toString();
var parentNodeArr = parentInnerHTML.split('');
if(parentInnerHTML != "null"){
var sel;
if (typeof win.getSelection != "undefined")
{
var rangeIndex = 0;
var parentIndex = 0;
var max = parentInnerHTML.length - 1;
var range = win.getSelection().toString();
var rangeNodeArr = range.split('');
var rangeLen = rangeNodeArr.length - 1;
for (parentIndex=0; parentIndex <= max; parentIndex++)
{
if(parentNodeArr[parentIndex] === rangeNodeArr[rangeIndex]){
if(rangeIndex === rangeLen){
break;
}
rangeIndex++;
}else{
rangeIndex = 0;
}
}
endOffset = parentIndex + 1;
startOffSet = parentIndex - rangeIndex;
}
console.log("startOffSet: " + startOffSet + " endOffset: " + endOffset);
return { startOffSet: startOffSet, endOffSet: endOffset };
}else{
console.log("Parent is null");
}
}