简体   繁体   中英

Getting wrong caret position in javascript

I am trying to insert token after selecting from context menu at the caret position inside a contenteditable div. I have managed to do that if the caret position is in a single line.

In my case the range offset value will set to 0 whenever other HTML tags appear ie when the line changes. I am using these two functions for getting the range which I've found somewhere in stackoverflow.

Any help is appreciated!

    function saveSelection() {
        var range = null;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
               return sel.getRangeAt(0);
            }
        } else if (document.selection && document.selection.createRange) {
            return document.selection.createRange();
        }
        return null;
    }

I think the problem is not with the no of line of content in your element which is contenteditable . Because you are using context menu with contenteditable div as you have mentioned. And when ever you click on the context menu it will get range value of that context menu.

So you should store the range value on certain variable before clicking on certain menu.

Since your code is incomplete I cannot relate any example with your code.

Here is one example hope this will help you:

 function pasteHtmlAtCaret(html) { var sel, range; if (window.getSelection) { // IE9 and non-IE sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); // Range.createContextualFragment() would be useful here but is // non-standard and not supported in all browsers (IE9, for one) var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } } 
 <input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); "> <div id="test" contenteditable="true"> Here is some nice text </div> 

jsfiddle link for the above mentioned code.

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