解决聊天窗口的输入框高度变化,引起中间滚动内容的跳动问题

场景:iphone  类似聊天窗口、有中间可滚动内容divB,输入框高度可以变化

问题:当输入框输入文字高度变化后,如输入了两三行的文字,则中间可滚动内容divB会跳动回到之前一行时的位置。

解决代码如下:通过async  和 await 解决

<template>
  <div class="main">
    <div class="title">标题</div>
    <div ref="container" class="container">
      <div v-for="(item, index) in 100" :key="index" class="item">item{{ index }}</div>
    </div>
    <div class="bottom">
      <van-field
        ref="inputText"
        v-model="inputText"
        class="input"
        rows="1"
        maxlength="1000"
        size="30"
        :autosize=" { maxHeight: 200, minHeight: 26 }"
        label=""
        type="textarea"
        placeholder="请输入..."
        :border="true"
        @focus="fieldFocus"
        @blur="fieldBlur"
      />
    </div>
    <div :style="{height:iosPlaceholderHeight,backgroundColor: '#FFFFFF' }"></div>
  </div>
</template>

<script>

export default {
  data () {
    return {
      iosPlaceholderHeight: '100px',
      inputText: '',
    };
  },

  computed: {

  },
  watch: {
    inputText: {
      handler(v) {
        if (v.length > 0) {
          this.chatBoxScrollToBottom(false);
        }
      },
      immediate: true
    }
  },
  activated() {

  },

  methods: {
    fieldFocus() {
      this.iosPlaceholderHeight = '400px';
      setTimeout(() => {
        this.chatBoxScrollToBottom(false);
      }, 100);
    },
    fieldBlur() {
      this.iosPlaceholderHeight = '100px';
    },
    // 设置滚动条到最底部
    async chatBoxScrollToBottom(smooth = true) {
      console.log('chatBoxScrollToBottom scrollHeight:', this.$refs.container?.scrollHeight);
      if (!smooth) {
        this.$nextTick(async () => {
          const chatBox = await this.$refs.container;
          chatBox?.scrollTo({ top: chatBox.scrollHeight });
        });
      } else {
        this.$nextTick(async () => {
          const chatBox = await this.$refs.container;
          chatBox?.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
        });
      }
    },
  },
};
</script>

<style  lang="less" scoped>
.main{
  padding-top: 88px;
  display: flex;
  flex-direction: column;
  height: 100%;
  .title{
    height: 100px;
  }

  .container{
    overflow: scroll;
    flex: 1;
    .item{
      height: 60px;
    }
  }
  .bottom{
    padding-top: 20px;
    background: #F7F8FA;
  }
  .input{
    width: 510px;
    line-height: 50px;
    font-size: 40px;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 6px;
    padding-top: 15px;
  }
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值