Change cursor position in the contenteditable div after changing innerHTML

后端 未结 3 1761
情书的邮戳
情书的邮戳 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:29

    You know which text you are replacing. So you know the position of that text . there only you going to put the new text. Then also the position is same.After writing new html , yu can set cursor.

    for eg

    I dont undertsand the question

    position of question is 5 an i replace it

    I dont undertsand the answer

    make the cursor position to 5

    http://ajaxian.com/archives/javascript-tip-cross-browser-cursor-positioning

    http://hartshorne.ca/2006/01/23/javascript_cursor_position/

    http://geekswithblogs.net/svanvliet/archive/2005/03/24/textarea-cursor-position-with-javascript.aspx

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2021-02-04 06:36

    The problem is that you're updating the whole innerHTML, but only a small part of it is changing. You can't use a regular expression and o a bulk replace. You need to scan the div and look for matches, create text ranges out of them and wrap the content with the span. See http://www.quirksmode.org/dom/range_intro.html , Programmatically creating a Range.

    However, I think this won't work if the cursor is in the text to be replaced, it's a start though.

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