IE TextRange select method not working properly

前端 未结 4 824
面向向阳花
面向向阳花 2020-12-28 11:50

I\'m having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediate

4条回答
  •  被撕碎了的回忆
    2020-12-28 12:27

    I've figured out a few methods for dealing with IE ranges like this.

    If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again:

    // Save position of cursor
    range.pasteHTML('')
    
    ...
    
    // Create new cursor and put it in the old position
    var caretSpan = iframe.contentWindow.document.getElementById("caret");
    var selection = iframe.contentWindow.document.selection;
    newRange = selection.createRange();
    newRange.moveToElementText(caretSpan);
    

    Alternatively, you can count how many characters precede the current cursor position and save that number:

    var selection = iframe.contentWindow.document.selection;
    var range = selection.createRange().duplicate();
    range.moveStart('sentence', -1000000);
    var cursorPosition = range.text.length;
    

    To restore the cursor, you set it to the beginning and then move it that number of characters:

    var newRange = selection.createRange();
    newRange.move('sentence', -1000000);
    newRange.move('character', cursorPosition);
    

    Hope this helps.

提交回复
热议问题