[英]How to get caret position within contenteditable div with html child elements?
[英]How to position a caret in a contenteditable div while ignoring the HTML tags?
以下代码根据插入号的值设置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标签的同时设置插入符号?
您可能需要递归搜索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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.