stash
This commit is contained in:
parent
53b35d0ee2
commit
046b23c225
1 changed files with 32 additions and 5 deletions
|
@ -18,7 +18,7 @@ export default {
|
|||
},
|
||||
data() {
|
||||
return {
|
||||
selection: null,
|
||||
selection: {start: 0, end: 0}
|
||||
};
|
||||
},
|
||||
emits: ['input'],
|
||||
|
@ -31,8 +31,35 @@ export default {
|
|||
}
|
||||
},
|
||||
onchange(event) {
|
||||
this.selection = window.getSelection();
|
||||
const div = this.$refs.text;
|
||||
const sel = window.getSelection();
|
||||
if (sel.rangeCount > 0) {
|
||||
this.selection.start = this.calculateOffset(div, sel.anchorNode, sel.anchorOffset);
|
||||
this.selection.end = this.calculateOffset(div, sel.focusNode, sel.focusOffset);
|
||||
}
|
||||
this.$emit('input', event.target.innerText);
|
||||
},
|
||||
calculateOffset(container, node, offset) {
|
||||
let position = 0;
|
||||
let found = false;
|
||||
const walk = (node) => {
|
||||
if (node === container) {
|
||||
found = true;
|
||||
return;
|
||||
}
|
||||
if (node.nodeType === 3) {
|
||||
position += node.length;
|
||||
} else {
|
||||
for (let i = 0; i < node.childNodes.length; i++) {
|
||||
walk(node.childNodes[i]);
|
||||
if (found) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(node);
|
||||
return position + offset;
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
|
@ -40,9 +67,9 @@ export default {
|
|||
if (this.selection) {
|
||||
const div = this.$refs.text;
|
||||
const range = document.createRange();
|
||||
console.log(this.selection.anchorOffset, this.selection.focusOffset);
|
||||
range.setStart(div, Math.min(this.selection.anchorOffset, div.childNodes[0].length));
|
||||
range.setEnd(div, Math.min(this.selection.focusOffset, div.childNodes[0].length));
|
||||
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));
|
||||
this.selection.removeAllRanges();
|
||||
this.selection.addRange(range);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue