首页 > 解决方案 > Nuxt.js 滚动到 div 元素的底部

问题描述

这段代码有什么问题?渲染 div 元素后,滚动必须在 div 元素的底部。scrollTop 在 func 之后不保存值

<main>
<div v-if="messages">
   <ul ref="messagesContainer">
       <li v-for="message in messages" :key="`${message.text}.${message.username}`">
         <Message :message="message" :username="username" />
       </li>
   </ul>
</div>
</main>
 mounted() {
    this.scrollToEnd();
  },
  methods: {
    scrollToEnd() {
      const height = this.$refs.messagesContainer.scrollHeight;
      this.$refs.messagesContainer.scrollTo(0,height)
      // doesnt work 
      // this.$refs.messagesContainer.scrollTop = height
    }
  }
 main {
    background-color: #fff;
    height: 56vh;
    ul {
      height: 100%;
      overflow: auto;
      flex: auto;
    }
  }

标签: scrollnuxt.js

解决方案


offsetHeight您可以通过如下属性 获取元素的 y 位置:var offsetTop = this.$refs.messagesContainer.offsetHeight;

您可以在此处找到有关offsetHeight,clientHeightscrollHeight属性的更多信息

请注意,您需要在元素上调用该scrollTo方法:window

例子:

methods: {
    scrollToEnd() {
      var scrollHeight = this.$refs.messagesContainer.offsetHeight;
      this.$refs.messagesContainer.scrollTop = scrollHeight;
    }
  }

希望这可以帮助 :)


推荐阅读