How to get caret position within contenteditable d

2020-02-05 05:13发布

I am working with a contenteditable div that will have the option to have inline html elements such as tags in the text flow.

At certain points I need to grab the caret position but have found that with the example code the position returned is incorrect if the caret is after an html child element.

I need a cross browser solution that will allow me to store the position of the caret so that it can be restored a split second later even with the presence of html elements in the text flow.

Example: http://jsfiddle.net/wPYMR/2/

2条回答
神经病院院长
2楼-- · 2020-02-05 06:00

I've answered a very similar question here: Editing Iframe Content in IE - problem in maintaining text selection

Here's a slightly simplified version of that answer:

If you're not changing the contents of the contenteditable element then the following functions will do. Call saveSelection() before doing whatever you need to do and restoreSelection() afterwards. If you are changing the content, I'd suggest using my Rangy library's save/restore selection module.

var saveSelection, restoreSelection;
if (window.getSelection) {
    // IE 9 and non-IE
    saveSelection = function() {
        var sel = window.getSelection(), ranges = [];
        if (sel.rangeCount) {
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                ranges.push(sel.getRangeAt(i));
            }
        }
        return ranges;
    };

    restoreSelection = function(savedSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        for (var i = 0, len = savedSelection.length; i < len; ++i) {
            sel.addRange(savedSelection[i]);
        }
    };
} else if (document.selection && document.selection.createRange) {
    // IE <= 8
    saveSelection = function() {
        var sel = document.selection;
        return (sel.type != "None") ? sel.createRange() : null;
    };

    restoreSelection = function(savedSelection) {
        if (savedSelection) {
            savedSelection.select();
        }
    };
}

Example use:

var sel = saveSelection();
// Do stuff here
restoreSelection(sel);
查看更多
姐就是有狂的资本
3楼-- · 2020-02-05 06:04

I posted a question about a cross-browser range/selection library and found some great stuff that I was able to solve all my needs with.

Here is my post: Cross Browser Selection Range Library?

What helped me best was Tim Down's rangy.

查看更多
登录 后发表回答