How to get caret position within contenteditable div with html child elements?

后端 未结 2 1142
醉酒成梦
醉酒成梦 2020-12-09 23:07

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 c

相关标签:
2条回答
  • 2020-12-09 23:10

    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);
    
    0 讨论(0)
  • 2020-12-09 23:20

    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.

    0 讨论(0)
提交回复
热议问题