如何在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','&nbsp;')
  // 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()
}