This commit is contained in:
j3d1 2024-06-06 21:06:06 +02:00
parent d96e5fd247
commit 9331b8c9e6

View file

@ -60,7 +60,31 @@ export default {
};
walk(container);
return position + offset;
},
findNode(container, offset) {
let position = 0;
let found = false;
let node = null;
const walk = (elem) => {
if (position + elem.length >= offset) {
found = true;
node = elem;
return;
}
if (elem.nodeType === 3) {
position += elem.length;
} else {
for (let i = 0; i < elem.childNodes.length; i++) {
walk(elem.childNodes[i]);
if (found) {
return;
}
}
}
};
walk(container);
return [node, offset - position]
},
},
watch: {
value() {
@ -68,8 +92,8 @@ export default {
const div = this.$refs.text;
const range = document.createRange();
console.log(this.selection);
range.setStart(div, Math.min(this.selection.anchorOffset, this.value.length));
range.setEnd(div, Math.min(this.selection.focusOffset, this.value.length));
range.setStart(...this.findNode(div, this.selection.start));
range.setEnd(...this.findNode(div, this.selection.end));
this.selection.removeAllRanges();
this.selection.addRange(range);
}