小程序底部input输入框,键盘弹起时页面整体上移问题解决

场景

存在问题:
小程序中,当input输入框位于页面底部时,输入框聚焦后键盘弹起,页面会整体上移,将输入框所在位置定位到键盘上方(图2)

解决思路:
键盘弹起时,页面其他元素不动不动,底部输入框跟随键盘上弹(图3)

效果图对比:
在这里插入图片描述

实现思路

1、input设置属性 :adjust-position=“false”,键盘弹起时,不上推页面
2、创建bottom变量,动态设置输入框距离底部的距离
2、input获取焦点事件中,监听键盘高度,赋值给bottom属性
3、input失去焦点事件中,监听键盘高度,重置bottom值为0

参考文档:adjust-position属性了解

注意:
由于获取的系统的尺寸单位都是 px ,给 bottom 设置的值单位也需要使用 px

代码示例:

html

<view class="message-input" :style="`bottom: ${bottom}px`">
  <!-- inner -->
  <view class="message-inner">
    <view class="icon-message" @click="openMessage"></view>
    <input
      type="text" 
      v-model="inputText" 
      placeholder="请输入" 
      :adjust-position="false" 
      @input="inputValueChange"
      @focus="inputBindFocus" 
      @blur="inputBindBlur" />
    <view class="icon-send"></view>
  </view>
  
  <!-- input未聚焦时,UI样式适配,底部增加32rpx -->
  <view v-if="bottom == 0" style="height: 32rpx;"></view>
</view>

js

export default {
    
    
  data() {
    
    
    return {
    
    
      bottom: 0, // 输入框距离页面底部距离(键盘高度px)
      inputText: '' // 输入框内容
    }
  },
  methods: {
    
    
    inputValueChange() {
    
    },
    inputBindFocus(e) {
    
    
      this.bottom = e.detail.height
    },
    inputBindBlur() {
    
    
      this.bottom = 0
    }
  }
}

css

.message-input {
    
    
  position: fixed;
  left: 0;
  // bottom: 0;
  z-index: 10;
  width: 750rpx;
  padding: 26rpx 36rpx;
  background: #FFFFFF;
  box-shadow: 0rpx 0rpx 17rpx 0rpx rgba(0, 26, 99, 0.1);
  border-radius: 48rpx 48rpx 0rpx 0rpx;
  
  .message-inner {
    
    
    display: flex;
    align-items: center;
    justify-content: space-between;
      
    .icon-message {
    
    
      width: 56rpx;
      height: 56rpx;
      background: url($oss-icon-message) no-repeat top left;
      background-size: 56rpx;
    }
      
    .icon-send {
    
    
      width: 88rpx;
      height: 88rpx;
      background: #4989FF url($oss-icon-send) no-repeat center;
      background-size: 56rpx;
      border-radius: 44rpx;
    }
      
    >input {
    
    
      width: 478rpx;
      height: 88rpx;
      padding: 0 20rpx;
      background: #EEF1F5;
      border-radius: 22rpx;
    }
      
  }
    
}

猜你喜欢

转载自blog.csdn.net/weixin_45559449/article/details/131773408