此代码仅chrome系列有效,适用于textarea和标记contenteditable的DIV
/**获取光标相对屏幕坐标
* @returns {DOMRect}
* */
function getAnchorPoint() {
let sel = window.getSelection();
if (!sel.focusNode) {
return { x: 0, y: 0, left: 0, top: 0, width: 0, height: 0 };
}
if (sel.focusNode.nodeName === '#text') {
let range = document.createRange();
range.selectNode(sel.focusNode);
range.setStart(sel.focusNode, sel.focusOffset);
return range.getBoundingClientRect();
} else {
return sel.focusNode.childNodes[sel.focusOffset - 1].getBoundingClientRect();
}
}