简体   繁体   English

如何在忽略HTML标签的情况下将插入符号放置在contenteditable div中?

[英]How to position a caret in a contenteditable div while ignoring the HTML tags?

Thes following code sets the caret based on the value of caret : 以下代码根据插入号的值设置caret

<div ref="editable" contenteditable="true">
  This text can be edited by the user. Right away.
</div>
<button type="button" @click="setCaret">Set caret</button>

setCaret () {
  const node = this.$refs.editable
  node.focus()
  const textNode = node.firstChild
  const caret = node.textContent.search('R')
  const range = document.createRange()
  range.setStart(textNode, caret)
  range.setEnd(textNode, caret)
  const sel = window.getSelection()
  sel.removeAllRanges()
  sel.addRange(range)
}

If you wrap the text inside p tags though: 如果将文本包装在p标签中,则:

<p>This text can be edited by the user.</p>
<p>Right away.</p>

You get this error: 您收到此错误:

App.vue?6b51:36Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset -1.(…)

How to modify the code so setCaret sets the caret while ignoring the HTML tags? 如何修改代码,以便setCaret在忽略HTML标签的同时设置插入符号?

You may need to search those nodes inside the div recursively: 您可能需要递归搜索div中的那些节点:

function findTextNode(node) {
  const childNodes = node.childNodes;
  if (childNodes.length > 0) {
    for(let i=0; i<childNodes.length; i++) {
      const child = childNodes[i];
      const result = findTextNode(child);
      if (result) {
        return result;
      }
    }
    return false;
  } else {
    const place = node.textContent.search('R');
    if (!node.tagName && place!==-1) {
      return node;
    }
    return false;
  }
}

Working fiddle here: http://jsfiddle.net/1x6knn37/ 在这里工作的小提琴: http : //jsfiddle.net/1x6knn37/

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

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