简体   繁体   中英

Caret no longer visible within contenteditable body tag after inserting a text node programmatically

I'm using Mozilla Firefox (83.0) on a Windows 10 Pro machine.

With a simple body tag with contenteditable attribute enabled, my caret disappears when I insert a text node. I did this exact same test on Chrome version 87.0.4280.88 and it doesn't behave this way

Here is a demo of this. Also you can find the fiddle at https://jsfiddle.net/dg47mkat/1/

 setTimeout(function(){ let range = document.getSelection().getRangeAt(0); let element = document.createElement('span'); range.insertNode(element); }, 10000);
 <html> <body contenteditable="true"> This is a test </body> </html>

Make sure to click somewhere within the text to see the caret being displayed, and wait the allotted timeout to run. After the insertion of the node, the caret is no longer visible unless you press on the arrow key or type a character.

Also please note, when there is text selection this does not occur.

Update 2020-12-11:12:40 I assumed that it would behave like it does in chrome, which is that the caret stays where it currently is, as is.

I was able to solve this problem in a way that works for both unselected and selected text.

Note: The change that I made was to clone the range and then re-apply that specific range after. It looks like in Firefox this is required, but in Chrome it is not. (refer to OP for version details)

 setTimeout(function(){ let range = document.getSelection().getRangeAt(0); let clonedRange = range.cloneRange(); let element = document.createElement('span'); range.insertNode(element); let selection = document.getSelection(); selection.removeAllRanges(); selection.addRange(clonedRange); }, 10000);
 <html> <body contenteditable="true" id="mybody">This is a test</body> </html>

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