0
帖下面的代碼設置的基礎上caret
值插入符號:如何將插入符號放在contenteditable div中而忽略HTML標籤?
<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標籤的同時設置插入符號?