I want to customized caret.
A question is that document.getSelection().getRangeAt(0).getClientRects()
return an empty array after I input a word in empty line, so I can’t get position of caret;
Under the same circumstances,an editable element has no this problem
calculate position of caret:
const selection = document.getSelection();
const anchorNode = selection?.anchorNode;
const range = selection.getRangeAt(0).cloneRange();
const rect = range.getClientRects()[0];
if (rect != undefined) {
setPos({
x: rect.left,
y: rect.top + window.scrollY,
height: rect.height,
show: true,
});
return;
}
if (anchorNode instanceof Element) {
const { x, y, height } = anchorNode.getBoundingClientRect();
const { fontSize } = getComputedStyle(anchorNode);
const computedCaretHeight = parseInt(fontSize) * 1.15;
setPos({
x: x,
y: y + height / 2 - computedCaretHeight / 2 + window.scrollY,
height: computedCaretHeight,
show: true,
});
return;
}
example: Glitch :・゚✧