简体   繁体   中英

Restore caret position when replacing editable div content

I have an editable div which allows tagging and on change the following code gets run to replace the innerHTML:

const setDisplayText = (element: HTMLDivElement) => {
   element.innerHTML = element.innerHTML.replace(/<span style="color: (.*?)">/g, '')
   element.innerHTML = element.innerHTML.replaceAll('</span>', '')
   element.innerHTML = element?.innerHTML.replace(/\$(.*?)( |&nbsp;|$)/g, `<span style="color: ${colors.blue_light}">$$$1</span>&nbsp;`)

However, when I do this the caret keeps returning to the start. I found one solution but it ignores line breaks.

Has anyone had to do anything similar?

The solution was to use draft js

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