思路:在微信小程序中,多行文本textarea聚焦位置一直能保持在键盘以上,那么位置动态改变的单行文本聚焦位置也可以;
解决方案:wx.pageScrollTo,将页面滚动到目标位置,用底部内边距撑满页面,以便可以滚动
代码:
wxml:input的父元素设置padding-bottom
<view class="wrap" style="padding-bottom: {{keyboardHeight}}px;" id="msInput">
<view wx:for="{{numList}}" wx:key="index">
<view>{{item}}</view>
</view>
<input class="ipt" value="{{inputVal}}" type="text" placeholder="请输入" confirm-hold="{{true}}" bindfocus="getKeyboardHeight" bindconfirm="pushNum" bindblur="handleblur" />
</view>
js
data: {
numList:[],
inputVal:"",
keyboardHeight:0,
scrollTop:0,
windowHeight:wx.getSystemInfoSync().windowHeight,
},
/**
* 组件的方法列表
*/
methods: {
getKeyboardHeight(e){
console.log("e",e);
this.setData({keyboardHeight:e.detail.height});
},
pushNum(e){
this.data.numList.push(e.detail.value);
this.setData({
numList:this.data.numList,
inputVal:"",
})
let { windowHeight,keyboardHeight } = this.data;//当前设备高度
const query = wx.createSelectorQuery().in(this)
query.select("#msInput").boundingClientRect();
query.selectViewport().scrollOffset();
query.exec((rect) => {
let current = rect[0]; //当前输入框位置信息(top、bottom)
let { scrollTop } = rect[1]; //当前滚动距离
console.log("当前滚动距离",scrollTop);
this.setData({
scrollTop: scrollTop,//把当前滚动条位置保存
});
const bottom = windowHeight - current.bottom; //输入框距离底部的位置
console.log("输入框距离底部的位置",bottom);
if (bottom < keyboardHeight) {//当输入框距离可视区域底部位置小于键盘高度时
//当输入框被遮挡时
let distance = keyboardHeight - bottom;
//只有通过增设置padding-bottom足够的值让页面有足够的长度,滚动方法才能生效
this.setData({
keyboardHeight,
});
wx.pageScrollTo({
selector: "#msInput", // 写法同css选择器
scrollTop: scrollTop + distance+20,
});
}
});
},
handleblur(){
this.setData({
keyboardHeight:0
})
},
}
css
.wrap{
margin-top: 200rpx;
display: flex;
flex-wrap: wrap;
}
.wrap .ipt{
flex: 1;
}