This commit is contained in:
j3d1 2024-06-06 21:06:06 +02:00
parent bf65ce3469
commit 7eb6073c3c

View file

@ -60,7 +60,31 @@ export default {
}; };
walk(container); walk(container);
return position + offset; 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: { watch: {
value() { value() {
@ -68,8 +92,8 @@ export default {
const div = this.$refs.text; const div = this.$refs.text;
const range = document.createRange(); const range = document.createRange();
console.log(this.selection); console.log(this.selection);
range.setStart(div, Math.min(this.selection.anchorOffset, this.value.length)); range.setStart(...this.findNode(div, this.selection.start));
range.setEnd(div, Math.min(this.selection.focusOffset, this.value.length)); range.setEnd(...this.findNode(div, this.selection.end));
this.selection.removeAllRanges(); this.selection.removeAllRanges();
this.selection.addRange(range); this.selection.addRange(range);
} }