我需要为我的应用程序创建聊天,并在进入聊天页面时显示最后的消息,我需要在div的底部自动滚动.

VueJs:VueJs:

<template>
    <div id="app">
        <div class="comments" v-chat-scroll>
            <div v-for="comment in comments">
                //What defines the comment
            </div>
        </div>
    </div>
</template>

Css:以下内容:

.comments {
    margin: 2.5rem auto 0;
    max-width: 60.75rem;
    padding: 0 1.25rem;
    height: 300px;
    overflow-y: scroll;
}

Typescript :

export default {

    mounted() {
        this.scrollToEnd();
    },

    methods: {

        scrollToEnd() {
            var container = this.$el.querySelector(".comments");
            var scrollHeight = container.scrollHeight;
            container.scrollTop = scrollHeight;
        },
    }
}

我试图通过给scroll赋予div的scllHeight来使用scllTop. ScllHeight获得较好的值(在本例中为300),但scllTop保持为0.

希望有人能帮上忙. 提前谢谢!

推荐答案

您的代码按原样为我工作,没有v-chat-scroll:

new Vue({
  el: '#app',
  data: {
    comments: Array.from({
      length: 50
    }, (_, i) => 'Comment ' + i).concat(['last comment - scroll here'])
  },
  mounted() {
    this.scrollToEnd();
  },

  methods: {

    scrollToEnd() {
      var container = this.$el.querySelector(".comments");
      var scrollHeight = container.scrollHeight;
      container.scrollTop = scrollHeight;
    },
  }
})
.comments {
  margin: 2.5rem auto 0;
  max-width: 60.75rem;
  padding: 0 1.25rem;
  height: 100px;
  overflow-y: scroll;
  border: 1px solid grey;
}

.comment {
  padding: 4px;
  border-top: 1px dotted grey;
}
<div id="app">
  <div class="comments">
    <div v-for="comment in comments">
      <div class="comment">{{comment}}</div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>

另外,v-chat-scroll指令做了同样的事情,它也适用于我:

new Vue({
  el: '#app',
  data:{
    comments: Array.from({length: 50}, (_,i) => 'Comment '+i).concat(['last comment - scroll here'])
  },
})
.comments {
  margin: 2.5rem auto 0;
  max-width: 60.75rem;
  padding: 0 1.25rem;
  height: 100px;
  overflow-y: scroll;
  border: 1px solid grey;
}

.comment{
  padding: 4px;
  border-top: 1px dotted grey;
}
<div id="app">
  <div class="comments" v-chat-scroll>
    <div v-for="comment in comments">
      <div class="comment">{{comment}}</div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-chat-scroll/dist/vue-chat-scroll.min.js"></script>

Css相关问答推荐

CSS动画与不正确的时间比率

如何允许在bslb中 Select 输入重叠卡片?

如何将另一种自定义位置 colored颜色 添加到三角形CSS中?

在 Next.js 中使用 .modules.scss 时未应用样式

没有字母间距的CSS悬停边框

如何增加 PrimeFlex 网格的间隙?

在 SVG 元素上方添加标签而不移动 SVG 元素

如何仅包装左侧内容

子组件的css会影响整个页面

无法更改 div 内链接的悬停 colored颜色

CSS3 - RotateY() 居中

在 vuetify 中跨 `default.vue` 和 `index.vue` 维护网格系统

使用 CSS 在悬停时转换 SVG 路径的填充属性

禁用输入的 CSS Select 器 type="submit"

如何将页脚保持在屏幕底部

如何在 CSS 中覆盖图像?

根据背景 colored颜色 反转 CSS 字体 colored颜色

我应该使用最大设备宽度还是最大宽度?

通过 Bootstrap4 对列进行排序

将 webkit 滚动条样式应用于指定元素