简体   繁体   English

以编程方式插入文本节点后,插入符号在 contenteditable 正文标记中不再可见

[英]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.我在 Windows 10 Pro 机器上使用 Mozilla Firefox (83.0)。

With a simple body tag with contenteditable attribute enabled, my caret disappears when I insert a text node.使用启用了 contenteditable 属性的简单正文标记,插入文本节点时我的插入符号会消失。 I did this exact same test on Chrome version 87.0.4280.88 and it doesn't behave this way我在 Chrome 版本 87.0.4280.88 上进行了完全相同的测试,但它的行为并非如此

Here is a demo of this.这是一个演示。 Also you can find the fiddle at https://jsfiddle.net/dg47mkat/1/您也可以在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.更新 2020-12-11:12:40 我假设它的行为就像在 chrome 中一样,即插入符号保持原样。

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.看起来在 Firefox 中这是必需的,但在 Chrome 中不是。 (refer to OP for version details) (版本详情参考OP)

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM