uni-app中input组件在用户手动移动光标位置或者获取焦点之后,如何获取当前光标位置
uni-app中input组件在用户手动移动光标位置或者获取焦点之后,如何获取当前光标位置
在input组件中,我需要在当前光标位置插入字符串,但目前之后[@input](/user/input)才会返回当前光标位置,用户手动移动光标位置之后,无法得到当前光标位置,有没有什么方法实现,比较紧急
3 回复
非常感谢
在 uni-app 中,可以通过监听 @input 事件获取输入内容,但光标位置需要借助 selectionchange 事件或 @tap 配合 createSelectorQuery 实现。以下是两种常用方案:
方案一:使用 @tap 或 @focus 结合 createSelectorQuery
在 input 组件上绑定 @tap 或 @focus 事件,通过 uni.createSelectorQuery() 获取光标位置。示例:
onTapInput(e) {
const query = uni.createSelectorQuery().in(this);
query.select('#myInput').fields({
rect: true,
size: true
}, res => {
// 计算光标位置(需结合点击坐标 e.detail.x 等)
console.log('光标位置计算:', res);
}).exec();
}
注意:此方法需手动计算点击坐标与输入框的相对位置,精度可能受限。
方案二:通过 selectionchange 事件(H5 端)
在 H5 环境中,可监听 selectionchange 事件获取光标位置:
// 仅在 H5 生效
document.addEventListener('selectionchange', () => {
const selection = window.getSelection();
console.log('光标位置:', selection.anchorOffset);
});
但此方法在非 H5 端(如小程序)不兼容,需条件编译。
推荐方案:结合 @input 与缓存
由于 uni-app 多端差异,最稳定的方式是:
- 在
@input事件中缓存最新的光标位置(通过event.detail.cursor获取,仅小程序端支持)。 - 在
@blur或@tap时更新位置缓存。 - 插入字符串时使用缓存的最后位置。
示例代码:
data() {
return {
cursorPos: 0
};
},
methods: {
onInput(e) {
// 小程序端可直接获取 cursor
if (e.detail.cursor !== undefined) {
this.cursorPos = e.detail.cursor;
}
// 其他端需通过输入框值长度估算(不精确)
},
insertText(text) {
// 根据 cursorPos 插入文本
const newValue = this.inputValue.slice(0, this.cursorPos) + text + this.inputValue.slice(this.cursorPos);
this.inputValue = newValue;
}
}


