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

需求

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

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

相关推荐
小满zs18 小时前
Next.js精通SEO第二章(robots.txt + sitemap.xml)
前端·seo
kyriewen18 小时前
你的首屏慢得像蜗牛?这6招让页面“秒开”
前端·面试·性能优化
算是难了18 小时前
Nestjs学习总结_3
前端·typescript·node.js
RONIN19 小时前
VUE开发环境配置基础(构建工具→单文件组件SFC→css预处理器sass→eslint)及安装脚手架
vue.js
yogalin199319 小时前
如何实现一个简化的响应式系统
前端
kyriewen1119 小时前
项目做了一半想重写?这套前端架构让你少走3年弯路
前端·javascript·chrome·架构·ecmascript·html5
HashTang19 小时前
我用 Cloudflare Workers + GitHub Actions 做了个 2.5 刀/月的 AI 日报,代码开源了
前端·ai编程·aiops
RONIN19 小时前
vue2、vue3区别之混入mixins和过滤器filter
vue.js
老王以为19 小时前
前端重生之 - 前端视角下的 Python
前端·后端·python
饭后一颗花生米19 小时前
2026 AI加持下前端学习路线:从入门到进阶,高效突破核心竞争力
前端·人工智能·学习