如何解决如何在contenteditable中转义格式化的元素?
我有一个contenteditable
部门。我试图弄清楚如何在<sup></sup>
事件中转义<code></code>
,keydown
等格式化元素:
代码
<div
id="editor"
contenteditable="true"
@input="editorInputHandler"
@keydown="editorKeydownHandler"
></div>
数据:
<p>test<sup>2{CURSOR_POSITION}</sup></p>
处理程序:
function editorKeydownHandler (event) {
const selection = window.getSelection()
const selectionTag = selection.anchorNode.parentNode.tagName
const selectionElementNode = selection.anchorNode
if (event.code === 'Enter' && selectionTag === 'SUP') {
// Creating a temp target for the cursor ?
// let span = document.createElement('span')
// selectionElementNode.parentNode.appendChild(span)
// ...
}
}
问题
如何通过enter
键按下将光标移出格式化元素(移至父标签的末尾),如下所示:
<p>test<sup>2{MOVE_CURSOR_FROM_HERE}</sup>{MOVE_CURSOR_TO_HERE}</p>
当前,当您点击enter
时,它会一直拖动格式:
<p>test<sup>2</sup></p><p><sup><br>{TYPING_WILL_CONTINUE_FROM_HERE}</sup></p>
解决方法
通过将偏移量设置为父级的长度,可以将所选内容的位置设置到父级元素的末尾。假设sup是您的上标元素。
let selection = window.getSelection();
selection.collapse(sup.parentNode,sup.parentNode.childNodes.length);
然后对focusNode进行相同操作,以确保未选择任何文本。
,为此找到了解决方案。如果有人知道更好的一个,请告诉我。
...
if (event.code === 'Enter' && selectionTag === 'SUP') {
event.preventDefault()
// Insert a 'space' symbol at the end
selection.anchorNode.parentNode.insertAdjacentHTML('beforeend',' ')
// Select the parent node
selection.selectAllChildren(selection.anchorNode.parentNode)
// Collapse selection to the end,effectively moving the cursor out of the formatted element
selection.collapseToEnd()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。