uni-app textarea设置自动获取焦点弹出软键盘
uni-app textarea设置自动获取焦点弹出软键盘
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | win10 | HBuilderX |
| Android | Android 12 | |
| OPPO | OPPO A9 |
示例代码:
<view class="textarea" id="textarea" :style="[{ height: height }]" >
<textarea v-model="txt" :focus="focus" :auto-height="true" class="input" maxlength="1500" placeholder="placeholder" :rows="rows" />
</view>
export default {
data() {
return {
txt: '', //反馈意见
placeholder: '请输入反馈意见', //占位符
rows: 3, //文本域默认显示行数
statusBarHeight: 32,
header_height: 44,
keyheight: 0,
height: 736,
focus: true
};
},
onLoad() {
this.initFullScreen();
},
onReady() {
uni.createSelectorQuery()
.select('#header')
.boundingClientRect(res => {
console.log(res);
this.header_height = res.height;
this.initFullScreen();
})
.exec();
},
methods: {
// 屏幕信息
initFullScreen() {
uni.getSystemInfo({
success: res => {
console.log(res);
this.statusBarHeight = res.statusBarHeight + 'px';
this.height = `calc(100vh - ${res.statusBarHeight + this.header_height + 'px'})`;
console.log(this.height);
// _this.height = `calc(100vh - ${_this.input_height + 'px'})`
}
});
},
}
};
操作步骤:
个人中心页(nvue)点击意见反馈按钮,跳转的意见反馈页面(vue)
预期结果:
进入到意见反馈页面首先获取焦点,弹出软键盘
实际结果:
获取到焦点,弹出软键盘,然后失去焦点,隐藏软键盘
bug描述:
自动获取焦点,弹出软键盘,然后失去焦点,隐藏软键盘
更多关于uni-app textarea设置自动获取焦点弹出软键盘的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
请提供一下完整复现问题的示例项目。只有片段代码无法复现问题
更多关于uni-app textarea设置自动获取焦点弹出软键盘的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在 uni-app 中,textarea 自动获取焦点后软键盘弹出又立即收起是常见问题,通常由以下原因导致:
- 页面切换动画干扰:页面跳转过程中,系统可能因动画未完成而误判焦点状态
- nvue 与 vue 页面差异:从 nvue 跳转到 vue 页面时,渲染引擎切换可能导致焦点丢失
- 时机问题:onReady 生命周期中执行查询可能触发页面重绘,影响焦点
解决方案:
方案一:延迟设置焦点
onReady() {
setTimeout(() => {
this.focus = true
}, 300) // 适当延迟确保页面渲染完成
}
方案二:使用 nextTick
import { nextTick } from 'vue'
onReady() {
nextTick(() => {
this.focus = true
})
}
方案三:避免在 onReady 中执行可能触发重绘的操作 将 boundingClientRect 查询移到 onLoad 或使用 mounted 生命周期:
mounted() {
uni.createSelectorQuery()
.select('#header')
.boundingClientRect(res => {
this.header_height = res.height
this.initFullScreen()
})
.exec()
// 设置焦点
setTimeout(() => {
this.focus = true
}, 100)
}
方案四:使用 uni.pageScrollTo 稳定页面
onReady() {
uni.pageScrollTo({
scrollTop: 0,
duration: 0,
success: () => {
setTimeout(() => {
this.focus = true
}, 50)
}
})
}
方案五:检查页面结构 确保 textarea 没有被其他元素遮挡或覆盖,特别是 fixed 定位的元素。
推荐方案: 结合方案二和方案三,在 mounted 中初始化布局,使用 nextTick 设置焦点:
mounted() {
// 初始化布局
this.initFullScreen()
// 延迟设置焦点
nextTick(() => {
setTimeout(() => {
this.focus = true
}, 100)
})
}

