这个问题好像只有ios会出现,安卓设置input属性adjust-position为true即可,可判断当前手机是ios还是安卓动态设置adjust-position
具体实现
html内容 注意不同输入框绑定的id要不一致
<input id="form-input-0" @keyboardheightchange="bindkeyboardheightchange" :adjust-position="false" @blur="scrollToInput(0)" type="text" v-model="text" />
// 页面底部添加 pageScrollHeight为要滚动的高度
<view :style="{height: pageScrollHeight + 'px'}"></view>
js内容
// 监听页面软键盘弹起手动推动页面
bindkeyboardheightchange(e) {
// 获取键盘高度
const height = e.detail.height;
const className = e.target.id;
if (height < 1) {
this.scrollToInput(0);
return;
}
try {
// 获取输入框底部距离手机顶部距离
this.createSelectorQuery()
.select(`#${className}`)
.boundingClientRect((res) => {
this.getWindowHeight().then(windowInfo=>{
// 获取手机高度
const windowHeight = windowInfo.windowHeight;
// 除去键盘的剩余高度 得到可视区域高度
let restHeight = windowHeight - height;
// 元素左下角坐标
let bottom = res.bottom + 20;
bottom = (Math.ceil(bottom * 100) / 100).toFixed(2)
// 只有当元素被软键盘覆盖的时候才上推页面
if (bottom <= restHeight) return;
// 现阶段需要滚动的大小
let scrollTop = bottom - restHeight;
this.scrollToInput(height, scrollTop);
}).catch(error=>{
console.log(error,"error");
const windowHeight = 500;
// 除去键盘的剩余高度
let restHeight = windowHeight - height;
// 元素左下角坐标
let bottom = res.bottom;
// 只有当元素被软键盘覆盖的时候才上推页面
if (bottom <= restHeight) return;
// 现阶段需要滚动的大小
let scrollTop = bottom - restHeight;
this.scrollToInput(height, scrollTop);
})
})
.exec();
} catch (error) {}
},
// 获取页面滚动条位置
getScrollOffset() {
return new Promise((resolve) => {
try {
wx.createSelectorQuery()
.selectViewport()
.scrollOffset((res) => {
resolve(res.scrollTop);
})
.exec();
} catch (error) {
console.log(error,"error");
resolve(0);
}
});
},
// 监听页面软键盘弹起手动推动页面
scrollToInput(keyboardHeight, scrollTop) {
let that = this;
if(keyboardHeight === 0){
this.pageScrollHeight = 0;
}
// 浏览器高度 800
// 键盘高度 270
// 输入框底部距离手机顶部距离
if (scrollTop) {
try {
this.getScrollOffset().then((lastScrollTop) => {
let scrollHeight = parseFloat(lastScrollTop ? lastScrollTop + scrollTop : scrollTop).toFixed(2);
that.pageScrollHeight = scrollHeight;
that.$nextTick(()=>{
uni.pageScrollTo({
scrollTop: scrollHeight, // 滚动到顶部,可以设置为其他高度
duration: 0, // 滚动动画时长,单位为毫秒
success() {
console.log('滚动成功');
},
fail(err) {
console.error('滚动失败', err);
}
});
})
});
} catch (error) {}
}
}
其他问题
1、如果页面底部有留白会导致不滚动或滚动高度较少
// 更改底部动态style
<view :style="{height: pageScrollHeight ? 'calc(100vh + ' + pageScrollHeight + 'px)' : '0px'}"></view>
2、uni.pageScrollTo不滚动
我遇到这个问题是因为页面高度问题,设置高度即可
height: auto !important;