我需要为我的应用程序创建一个聊天,并在进入聊天页面时显示最后的消息,我需要在 div 底部自动滚动。
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;
},
}
}
我尝试通过给与滚动的div的scrollHeight来使用scrollTop。 scrollHeight 获得合适的值(在本例中为 300),但scrollTop 保持在 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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a782f0ecba" rel="noreferrer noopener nofollow">[email protected]</a>/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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c7c4d4f1839fc9" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-chat-scroll/dist/vue-chat-scroll.min.js"></script>
关于css - 如何在启动时滚动 div 底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75888100/