跳转至

输入框与里面内容错位

input键盘弹出时,滚动页面,输入框内容错位问题

uniapp文档input

存在的问题:页面 最外层使用了 scroll-view,在安卓手机滚动页面的时候输入框与输入框里面内容错位,

方案

  1. always-embed=true (官方介绍仅ios下生效)
  2. 将父元素设置的高度100vh去掉好了 (不使用scroll-view,需要使用滚动到某个id位置的话可以使用 uni.pageScrollTo)
  3. 继续使用scroll-view ,css设置 height: calc(100vh - 1px);

demo

<template>
  <scroll-view class="msg" scroll-y>
    {{ inputValue }} - {{ keyboardHeight }}
    <view class="action-wrapper" @click="handleClickInput">
      <view class="action"> 请输入内容 </view>
    </view>
    <view :class="['input-wrapper']" :style="{ bottom: keyboardHeight + 'px' }">
      <input
        type="text"
        class="input"
        placeholder="请输入内容"
        :maxlength="100"
        :cursor-spacing="20"
        confirm-type="done"
        v-model="inputValue"
        :adjust-position="false"
        :focus="inputFocus"
        @focus="onFocus"
        @blur="onBlur"
        @confirm="handleClickSendMsg"
      />
      <view class="send-btn" @click="handleClickSendMsg">发送</view>
    </view>
  </scroll-view>
</template>

<script>
export default {
  data() {
    return {
      description: "适配聊天框的问题",
      inputValue: "",
      keyboardHeight: -100,
      inputFocus: false,
    };
  },
  methods: {
    // 唤起键盘,获取焦点
    handleClickInput() {
      this.inputFocus = true;
    },
    // 获取焦点逻辑
    onFocus(e) {
      const { height } = e.detail;
      this.keyboardHeight = height;
      console.log("onFocus", e);
    },
    // 失去焦点逻辑
    onBlur(e) {
      this.keyboardHeight = -100;
      this.inputFocus = false;
      console.log("onBlur", e);
    },
    // ------------
    handleClickSendMsg() {
      console.log("发送消息", this.inputValue);
    },
  },
};
</script>
<style lang="scss" scoped>
.msg {
  height: calc(100vh - 1px);
  .action-wrapper {
    .action {
      position: fixed;
      bottom: 0;
      padding-bottom: Max(env(safe-area-inset-bottom), 44rpx);
      left: 0;
      right: 0;
      height: 100rpx;
      background-color: #fff;
      border-top: 1rpx solid #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
    }
  }
  .input-wrapper {
    background: #fff;
    box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    //
    width: 100%;
    box-sizing: border-box;
    position: fixed;
    left: 0;
    transition: bottom 0.1s ease-in-out;
    .input {
      flex: 1;
      height: 64rpx;
      line-height: 64rpx;
      padding: 0 24rpx;
      border-radius: 44rpx;
      background-color: #f5f5f5;
      color: #333333;
      font-size: 28rpx;
      margin-right: 20rpx;
    }
    .send-btn {
      width: 96rpx;
      height: 64rpx;
      border-radius: 44rpx;
      background-color: #45d0ff;
      color: #ffffff;
      font-size: 28rpx;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>