Fix and refactor getCaretPosition (#1782)
This commit is contained in:
@@ -6,16 +6,21 @@ import {
|
|||||||
|
|
||||||
// Taken from https://stackoverflow.com/a/46902361
|
// Taken from https://stackoverflow.com/a/46902361
|
||||||
export function getCaretPosition(node) {
|
export function getCaretPosition(node) {
|
||||||
var range = window.getSelection().getRangeAt(0),
|
const selection = window.getSelection();
|
||||||
preCaretRange = range.cloneRange(),
|
|
||||||
caretPosition,
|
if (selection.rangeCount === 0) {
|
||||||
tmp = document.createElement('div');
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const range = selection.getRangeAt(0);
|
||||||
|
const preCaretRange = range.cloneRange();
|
||||||
|
const tempElement = document.createElement('div');
|
||||||
|
|
||||||
preCaretRange.selectNodeContents(node);
|
preCaretRange.selectNodeContents(node);
|
||||||
preCaretRange.setEnd(range.endContainer, range.endOffset);
|
preCaretRange.setEnd(range.endContainer, range.endOffset);
|
||||||
tmp.appendChild(preCaretRange.cloneContents());
|
tempElement.appendChild(preCaretRange.cloneContents());
|
||||||
caretPosition = tmp.innerHTML.length;
|
|
||||||
return caretPosition;
|
return tempElement.innerHTML.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Might not need this anymore
|
// Might not need this anymore
|
||||||
|
|||||||
Reference in New Issue
Block a user