简体   繁体   中英

how can I get the Character offset related to body with Range Object and window.getSelection()?

I'm writing a client-side application with Javascript, I'm using 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 know the character offset related to body element. I found a function with counts 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;
}

That looks like a function from one of my answers. I overcomplicated it a little; see this answer for a simpler function that works in IE < 9 as well: https://stackoverflow.com/a/4812022/96100 . You can just pass in document.body as the node parameter. Also, please read the part in the linked answer about the shortcomings of this approach.

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

Has this been "solved" in a way to get the caretOffset inside innerText and not textContent ?

I've got a solution that works, after a select via double-click is made ...

A better way to extract innerText around getSelection()

Is there even a better way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM