Change cursor position in the contenteditable div after changing innerHTML

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

提交回复
热议问题