如何在忽略HTML标签的同时将插入符号置于可信任的div中?

时间:2016-12-03 06:53:31

标签: javascript vue.js

以下代码根据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)
}

如果您将文本包装在p标签内:

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

您收到此错误:

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

如何修改代码以便setCaret设置插入符号而忽略HTML标记?

1 个答案:

答案 0 :(得分:2)

您可能需要递归搜索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;
  }
}

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