Commit 908dc860 authored by youjie's avatar youjie
parents eaaf1aff 5a7bc4ce
......@@ -21,6 +21,7 @@
},
methods: {
changeText: function () {
var that = this;
let sel = window.getSelection();
let offset = sel.anchorOffset;
if (this.textLength && this.$el.innerText.length > this.textLength) {
......@@ -32,16 +33,50 @@
var range = sel.getRangeAt(0);
var textNode = range.startContainer;
var textNodeName = textNode.nodeName;
console.log("textNode", textNode.nodeName);
if (textNodeName == "#text") {
range.setStart(textNode, offset);
sel.removeAllRanges();
sel.addRange(range);
} else {
that.setCaretPosition(that.$el, offset);
}
} catch (err) {
console.log(err);
}
}, 0);
},
//重置div光标位置
setCaretPosition(element, offset) {
var range = document.createRange();
var sel = window.getSelection();
//select appropriate node
var currentNode = null;
var previousNode = null;
for (var i = 0; i < element.childNodes.length; i++) {
//save previous node
previousNode = currentNode;
//get current node
currentNode = element.childNodes[i];
//if we get span or something else then we should get child node
while (currentNode.childNodes.length > 0) {
currentNode = currentNode.childNodes[0];
}
//calc offset in current node
if (previousNode != null) {
offset -= previousNode.length;
}
//check whether current node has enough length
if (offset <= currentNode.length) {
break;
}
}
//move caret to specified offset
if (currentNode != null) {
range.setStart(currentNode, offset);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment