uni-app升级hbuilder后,h5页面中input使用:focus绑定聚焦时光标指定位置无效,总是定位到最开头的位置
uni-app升级hbuilder后,h5页面中input使用:focus绑定聚焦时光标指定位置无效,总是定位到最开头的位置
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Mac | 12.1 | HBuilderX |
示例代码:
<view class="input-item">
<template v-for="(item, index) in numArr">
<input
:focus="numFocusIndex === index"
type="number"
class="item"
:key="index"
:value="item"
:maxlength="1"
@input="handleIptChange($event, index, 'numArr')"
@keyup.delete="handleIptKeyup($event, index, 'numArr')"
/>
</template>
</view>
handleIptKeyup(e, index, arr) {
// 监听退格键盘
if (index !== 0) {
this.numFocusIndex = index - 1;
}
},
handleIptChange(e, index, arr) {
this[arr][index] = e.detail.value;
if (e.detail.value !== "") {
// 输入光标如下一个
if (index !== 6) {
this.numFocusIndex = index + 1;
}
}
},
`更多关于uni-app升级hbuilder后,h5页面中input使用:focus绑定聚焦时光标指定位置无效,总是定位到最开头的位置的实战教程也可以访问 https://www.itying.com/category-93-b0.html
你先用你同事的版本先用着 你用3.3.13这个版本也是没有问题的
更多关于uni-app升级hbuilder后,h5页面中input使用:focus绑定聚焦时光标指定位置无效,总是定位到最开头的位置的实战教程也可以访问 https://www.itying.com/category-93-b0.html
请问这个在新版能修复吗?一直用着旧版没法用Hbuilder自带的预览功能,今天更新了最新版发现这个bug还是没有修复
在 uni-app 中,如果你在升级 HBuilder 后发现 input 元素在 :focus 时无法正确设置光标位置,总是定位到最开头的位置,可能是由于以下原因导致的:
1. Vue 的异步更新机制
Vue 的更新是异步的,可能在 :focus 事件触发时,input 的值还没有完全更新,导致光标位置不正确。你可以尝试使用 nextTick 来确保 DOM 更新完成后再设置光标位置。
this.$nextTick(() => {
this.$refs.input.focus();
});
2. v-model 和 :value 的冲突
如果你同时使用了 v-model 和 :value,可能会导致 input 的值更新不一致,从而影响光标位置。确保只使用 v-model 来绑定 input 的值。
<input v-model="inputValue" ref="input" />
3. input 的 type 属性
某些 input 的 type 属性(如 password、number 等)可能会导致光标位置问题。尝试将 type 设置为 text,看看问题是否依然存在。
<input type="text" v-model="inputValue" ref="input" />
4. input 的 autofocus 属性
如果你使用了 autofocus 属性,可能会导致光标位置问题。尝试移除 autofocus 属性,手动调用 focus() 方法。
<input v-model="inputValue" ref="input" />
this.$nextTick(() => {
this.$refs.input.focus();
});
5. input 的 value 属性
如果你直接操作 input 的 value 属性,可能会导致光标位置问题。确保通过 v-model 来更新 input 的值。
<input v-model="inputValue" ref="input" />
6. input 的 selectionStart 和 selectionEnd
如果你需要手动设置光标位置,可以使用 selectionStart 和 selectionEnd 属性。
this.$nextTick(() => {
const input = this.$refs.input;
input.focus();
input.setSelectionRange(2, 2); // 将光标设置到第2个字符后
});
7. HBuilder 版本问题
如果以上方法都无法解决问题,可能是 HBuilder 版本本身存在 bug。你可以尝试回退到之前的版本,或者等待官方修复。
8. 检查其他代码
检查是否有其他代码(如自定义指令、插件等)可能影响了 input 的行为。
示例代码
以下是一个完整的示例,确保在 input 聚焦时正确设置光标位置:
<template>
<div>
<input v-model="inputValue" ref="input" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: 'Hello World'
};
},
methods: {
focusInput() {
this.$nextTick(() => {
const input = this.$refs.input;
input.focus();
input.setSelectionRange(2, 2); // 将光标设置到第2个字符后
});
}
}
};
</script>

