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

需求

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

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

相关推荐
何双新2 小时前
Odoo AI 智能查询系统
前端·人工智能·python
秋名山大前端8 小时前
Chrome GPU 加速优化配置(前端 3D 可视化 / 数字孪生专用)
前端·chrome·3d
今天不要写bug8 小时前
antv x6实现封装拖拽流程图配置(适用于工单流程、审批流程应用场景)
前端·typescript·vue·流程图
luquinn8 小时前
实现统一门户登录跳转免登录
开发语言·前端·javascript
用户21411832636029 小时前
dify案例分享-5分钟搭建智能思维导图系统!Dify + MCP工具实战教程
前端
augenstern4169 小时前
HTML(面试)
前端
excel9 小时前
前端常见布局误区:1fr 为什么撑爆了我的容器?
前端
烛阴9 小时前
TypeScript 类型魔法:像遍历对象一样改造你的类型
前端·javascript·typescript
vayy9 小时前
uniapp中 ios端 scroll-view 组件内部子元素z-index失效问题
前端·ios·微信小程序·uni-app
专注API从业者9 小时前
基于 Node.js 的淘宝 API 接口开发:快速构建异步数据采集服务
大数据·前端·数据库·数据挖掘·node.js