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

需求

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

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

相关推荐
一渊之隔24 分钟前
微信小程序在用户拒绝授权后无法使用wx.opensetting再次获取定位授权
微信小程序·小程序
雪碧聊技术38 分钟前
深入解析Vue中v-model的双向绑定实现原理
前端·javascript·vue.js·v-model
快起来别睡了40 分钟前
手写 Ajax 与 Promise:从底层原理到实际应用
前端
打不着的大喇叭1 小时前
uniapp的光标跟随和打字机效果
前端·javascript·uni-app
无我Code2 小时前
2025----前端个人年中总结
前端·年终总结·创业
程序猿阿伟2 小时前
《前端路由重构:解锁多语言交互的底层逻辑》
前端·重构
Sun_light2 小时前
6个你必须掌握的「React Hooks」实用技巧✨
前端·javascript·react.js
爱学习的茄子2 小时前
深度解析JavaScript中的call方法实现:从原理到手写实现的完整指南
前端·javascript·面试
莫空00002 小时前
Vue组件通信方式详解
前端·面试
呆呆的心2 小时前
揭秘 CSS 伪元素:不用加标签也能玩转出花的界面技巧 ✨
前端·css·html