Change cursor position in the contenteditable div after changing innerHTML

后端 未结 3 1765
情书的邮戳
情书的邮戳 2021-02-04 06:02

I have a simple contenteditable div with some text in it. On onkeyup event i want to replace whole content (innerHTML) of the div based on regex.

For example,

HT

3条回答
  •  灰色年华
    2021-02-04 06:33

    I took this from another forum. It solved my problem.

    Ok, I managed to work around it, here's the solution if anyone's interested:

    Store the selection x, y:

    Code:

    cursorPos=document.selection.createRange().duplicate();
    clickx = cursorPos.getBoundingClientRect().left; 
    clicky = cursorPos.getBoundingClientRect().top;
    

    Restore the selection:

    Code:

    cursorPos = document.body.createTextRange();
    cursorPos.moveToPoint(clickx, clicky);
    cursorPos.select();
    

    You can see it working here:

    http://www.tachyon-labs.com/sharpspell/

提交回复
热议问题