繁体   English   中英

根据字符偏移在可编辑的 div 中设置 cursor position

[英]Setting cursor position within editable div based on character offset

好的,所以我需要一个“输入”,允许突出显示“无效”的部分。

由于我无法通过实际输入来做到这一点,因此我使用的是带有contenteditable=truediv 该算法在概念上相当简单:

  • keyup
    • 验证输入
    • 用具有正确 class 的span替换div的 innerHtml
    • 使用 CSS 样式错误
    • 恢复 cursor position st 用户可以继续输入

正是最后一部分给了我一些问题。

我找到了 https://stackoverflow.com/a/4812022/3322533 ,它可以很好地获得偏移量,但是,我尝试恢复它,

function setCursorPositionWithin(element, pos) {  
  const doc = element.ownerDocument || element.document;
  const win = doc.defaultView || doc.parentWindow;
  let sel;
  const newPosition = document.createRange()
  newPosition.setStart(element, 0)
  newPosition.setEnd(element, 0)

  element.focus();

  if (typeof win.getSelection != "undefined") {
    sel = win.getSelection();
    if (sel.rangeCount > 0) {
        sel.removeAllRanges();
    }
      newPosition.selectNodeContents(element);
      newPosition.setStart(newPosition.startContainer, pos)
      newPosition.setEnd(newPosition.endContainer, pos);
      sel.addRange(newPosition)

  } else if ((sel = doc.selection) && sel.type != "Control") {
    throw Error('IE not supported')
  }
}

失败是因为

Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset 11.
    at setCursorPositionWithin

如何正确构建此范围?

提琴手

好的,所以问题似乎正是它所说的:范围试图在第n个 position 处设置 cursor position,如果n足够大,则可能不存在。

如果我们不只是将错误部分用类包装在span中,而是将每个字符包装在它自己的 span 中,那么这个问题是可以解决的。

我还没有弄清楚为什么getCursorPositionWithin会以这种方式工作,如果是这样的话,但我想这是一个不同的问题。

暂无
暂无

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

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