场景:iphone 类似聊天窗口、有中间可滚动内容divB,输入框高度可以变化
问题:当输入框输入文字高度变化后,如输入了两三行的文字,则中间可滚动内容divB会跳动回到之前一行时的位置。
解决代码如下:通过async 和 await 解决
- <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>
-
- <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>