TinyMCE contenteditable获取光标位置时选择范围异常问题
解决TinyMCE可编辑区域光标位置获取引发的选择异常
我要给TinyMCE的contenteditable区域做滚动动画,得先拿到光标/插入符的实际位置。之前写了个函数用来获取光标“末端”位置:
function getPositionFromSelection (selection, position = 'end') { const prevRange = selection.getRangeAt(0).cloneRange() if (position === 'start') { selection.collapseToStart() } else { selection.collapseToEnd() } const caret = selection.getRangeAt(0).getBoundingClientRect() selection.removeAllRanges() selection.addRange(prevRange) return caret.top }
但用这个方法时,缩小选择范围会出现异常:光标直接跳到选择范围的另一端,还会把选择范围扩大。
问题出在直接修改了页面上的实际选择实例(也就是传入的selection对象),哪怕之后恢复了Range,浏览器的选择状态还是会被干扰。改成用临时Selection来操作就没问题了:
function getPositionFromSelection(selection, position = 'end') { // 克隆原Range,避免影响实际选择状态 const clonedRange = selection.getRangeAt(0).cloneRange(); // 创建临时Selection来操作 const tempSelection = window.getSelection(); tempSelection.removeAllRanges(); tempSelection.addRange(clonedRange); if (position === 'start') { tempSelection.collapseToStart(); } else { tempSelection.collapseToEnd(); } const caretTop = tempSelection.getRangeAt(0).getBoundingClientRect().top; // 清理临时Selection tempSelection.removeAllRanges(); return caretTop; }
这样操作的是克隆出来的Range和临时Selection,完全不会影响页面上的实际选择状态,也就不会出现光标跳转、选择范围异常的问题了。
内容的提问来源于stack exchange,提问作者Pachari
相关产品推荐
相关产品推荐

