【小程序】文本框聚焦时,弹出的键盘遮挡住文本框如何处理

需求

现在需要实现一个功能,当在微信小程序点击聚焦输入框时,页面自动滚动,使输入框显示在弹出的键盘上方,避免被键盘遮挡。

iso的微信小程序自带这个优化,不需要额外处理。

安卓或其他系统的微信小程序需要这个处理。

实现方法

通过input的聚焦事件触发计算页面滚动达到效果,定位滚动位置的需求使用的参数scroll-top来实现

代码

html 复制代码
<scroll-view
      :scroll-top="curScrollTop "
      scroll-y="true"
      @scroll="scroll"
      show-scrollbar
      :style="{ height: height }"
>
<input class="my-input" @focus="inputFocus"></input>
</scroll-view>
javascript 复制代码
//页面滚动时记录滚动高度
scroll(e) {
  this.curScrollTop = e.detail.scrollTop;
},
//聚焦事件
inputFocus(e,index) {
      let _this = this;
      const query = wx.createSelectorQuery();//这里有坑,如果输入框在子组件里,需要使用uni.createSelectorQuery().in(this.$refs.fault.$refs.MyTextarea[index])这种方法来定位到其组件内的作用域
      query
        .select(".my-input")//通过类名获取输入框
        .boundingClientRect((data) => {
          console.log(_this.scrollTop);
          console.log("得到布局位置信息" + JSON.stringify(data));
          console.log("节点离页面顶部的距离为" + data.top);
          uni.getSystemInfo({
            success: function (res) {
              const platform = res.platform.toLowerCase();
              if (platform === "ios") {
                console.log("当前设备是iOS");
                //ios不做任何处理
              } else {
                console.log("当前设备不是iOS");
                if (data.top > 200) {
                //不是ios时处理滚动高度
                  _this.scrollTop = _this.curScrollTop + data.top - 200;
                }
              }
            },
          });
        })
        .exec();
    }

如果输入框位于子组件而非处理滚动事件的组件内, const query = wx.createSelectorQuery()的方法定义query将会找不到输入框元素;需要使用uni.createSelectorQuery().in(this. r e f s . f a u l t . refs.fault. refs.fault.refs.MyTextarea[index])这样类似的语句先定位到输入框所在的子组件

相关推荐
aklry3 分钟前
uniapp三步完成一维码的生成
前端·vue.js
说私域7 分钟前
基于开源AI智能名片链动2+1模式的S2B2C商城小程序:门店私域流量与视频号直播融合的生态创新研究
人工智能·小程序·开源
Rubin9310 分钟前
判断元素在可视区域?用于滚动加载,数据埋点等
前端
爱学习的茄子10 分钟前
AI驱动的单词学习应用:从图片识别到语音合成的完整实现
前端·深度学习·react.js
用户38022585982411 分钟前
使用three.js实现3D地球
前端·three.js
程序无bug13 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
zhanshuo13 分钟前
鸿蒙UI开发全解:JS与Java双引擎实战指南
前端·javascript·harmonyos
JohnYan13 分钟前
模板+数据的文档生成技术方案设计和实现
javascript·后端·架构
撰卢37 分钟前
如何提高网站加载速度速度
前端·javascript·css·html
10年前端老司机42 分钟前
在React项目中如何封装一个可扩展,复用性强的组件
前端·javascript·react.js