How can I get the character offset associated with the body with a Range object and window.getSelection ()?

I am writing a client application with Javascript, I use the following functions:

function creation() { var userSelection; if (window.getSelection) { userSelection = window.getSelection(); } else if (document.selection) { // should come last; Opera! userSelection = document.selection.createRange(); } var rangeObject = getRangeObject(userSelection); var startOffset = rangeObject.startOffset; var endOffset = rangeObject.endOffset; var startCon = rangeObject.startContainer; var endCon = rangeObject.endContainer; var myRange = document.createRange(); myRange.setStart(startCon,rangeObject.startOffset); myRange.setEnd(endCon, rangeObject.endOffset); $('#result').text(myRange.toString()); } function getRangeObject(selectionObject) { if (selectionObject.getRangeAt) { var ret = selectionObject.getRangeAt(0); return ret; } else { // Safari! var range = document.createRange(); range.setStart(selectionObject.anchorNode, selectionObject.anchorOffset); range.setEnd(selectionObject.focusNode, selectionObject.focusOffset); return range; } } 

I need a way to find out the character offset associated with the body element. I found a function to count the character in an element:

 function getCharacterOffsetWithin(range, node) { var treeWalker = document.createTreeWalker( node, NodeFilter.SHOW_TEXT, function (node) { var nodeRange = document.createRange(); nodeRange.selectNode(node); return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; }, false ); var charCount = 0; while (treeWalker.nextNode()) { charCount += treeWalker.currentNode.length; } if (range.startContainer.nodeType == 3) { charCount += range.startOffset; } return charCount; } 
+4
source share
2 answers

This seems like a function from one of my answers. I lightened it a little; see this answer for a simpler function that works in IE <9: fooobar.com/questions/21551 / .... You can simply pass document.body as a node parameter. Also, read part of the related answer about the disadvantages of this approach.

Here's a live demo: http://jsfiddle.net/PzQjA/

+1
source

Was it "solved" in such a way as to get caretOffset inside innerText, and not textContent?

I have a solution that works after double click selection ...

Best way to extract innerText around getSelection ()

Is there any better way?

0
source

Source: https://habr.com/ru/post/1388893/


All Articles