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

需求

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

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.MyTextareaindex)这样类似的语句先定位到输入框所在的子组件

相关推荐
猪猪拆迁队几秒前
跨电脑复制共享-局域网直连踩坑
前端·后端·go
静默回滚1 分钟前
逐帧处理视频的内存去哪了,我从看错读数查到没排队
前端
重庆穿山甲17 分钟前
我们不做「看起来很聪明」的知识库:一套企业级 RAG 平台的 37 屏真机实录
前端
风花一世月24 分钟前
🛩️ 我把一段夕阳飞行做成了能按键驾驶的网页(24 秒四段航线,在线直接玩)
前端
用户114818678948432 分钟前
实现一个「配置驱动」的动态表格组件(Vue + Element UI)
前端
数据掘金35 分钟前
小程序分享参数在页面栈中的传递
前端
乐享qicheng35 分钟前
1,自定义表单通俗理解-PC设计APP渲染
前端
为你学会写情书36 分钟前
大屏适配别再只会 transform: scale 了,这套方案更稳
前端
孤独的神36 分钟前
《AI 成了我的工位搭子,也成了我的焦虑来源》
前端
行者全栈架构师40 分钟前
给开源 Rust 工具加一个新检查项,TRAE 帮我从想法跑到构建产物:全链路实战
前端·算法·架构