0
我正在嘗試查找選擇的文本開始和結束。JavaScript選擇相對於父項的文本位置
我的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.
的工作示例在這裏:
http://jsfiddle.net/TjXEG/496/
無法在我的瀏覽器中重現該問題。您正在使用哪個瀏覽器和版本?從技術上講,這個問題不應該存在,因爲'HTMLDivElement'繼承自['Node'](https://developer.mozilla.org/en-US/docs/Web/API/Node) –
我正在使用最新的firefox 31.0和chrome版本36.0。 – Hassan
你檢查小提琴給你的錯誤嗎? –