JS获取鼠标光标位置以及设置
js获取鼠标光标位置,具体思路:
- 鼠标点击时记录光标位置(keyup)
- 内容发生改变时记录光标位置(MutationObserver)
- 左右键移动光标时记录坐标位置(keyup)
由于MutationObserverInit 不支持IE11以下版本,因此需要引用“mutationobserver-shim”,npm i mutationobserver-shim
记录光标位置
recordSelection() {
const selection = window.getSelection() || document.getSelection();
if (selection) {
const currentRange = selection.getRangeAt(0);
this.selection = selection;
this.currentRange = currentRange;
}
}
editView:可输入容器
鼠标点击时记录光标位置(keyup)
editView.addEventListener("mouseup", this.recordSelection);
内容发生改变时记录光标位置(MutationObserver)
const config: MutationObserverInit = {
attributes: true,
childList: true,
subtree: true,
characterData: true
};
const observer = new MutationObserver(() => {
this.recordSelection();
});
observer.observe(editView, config);
this.observer = observer;
左右键移动光标时记录坐标位置(keyup)
editView.addEventListener("keyup", (e: KeyboardEvent) => {
const keynum: number = window.event ? e.keyCode : e.which;
if (keynum >= 37 && keynum <= 40) {
this.recordSelection();
}
});
设置光标位置
restoreSelection() {
const selection =
this.selection || window.getSelection() || document.getSelection();
const range = this.currentRange;
if (selection && range) {
selection.removeAllRanges();
selection.addRange(range);
}
}
完整代码
<template>
<div class="edit">
<VEmojiPicker
class="emoji-picker"
v-show="showEmoji"
:pack="emojiNatives"
:showSearch="false"
@select="selectEmoji"
/>
<div class="toolbar">
<i
class="toolbar-item iconfont icon-biaoqing3"
@click="openEmojiPicker"
></i>
<i class="toolbar-i