【问题标题】:Auto scroll to bottom of the page using overflow auto使用溢出自动滚动到页面底部
【发布时间】:2018-07-11 13:27:30
【问题描述】:

我使用 vue js 创建了一个聊天应用程序。我使用溢出:自动为我的 div。我想要的是在 div 的底部自动滚动,这样用户就不会再单击滚动来查看最新消息。我的代码不起作用,并且在控制台中没有显示错误。任何帮助,将不胜感激。谢谢。

这里是代码

    <template>
 <div class="panel-block">
        <div class="chat" v-if="chats.length != 0" id="myDiv">
         <div v-for="chat in chats" style="overflow: auto;">
             <div class="chat-right" v-if="chat.user_id == userid">
                 {{ chat.chat }}
             </div>
             <div class="chat-left" v-else>

                 {{ chat.chat}}
             </div>
         </div>

        </div>
        <div v-else class="no-message">
            <br>
            There are no messages
        </div>
        <chat-composer v-bind:userid="userid" v-bind:chats="chats" v-bind:adminid="adminid"></chat-composer>
 </div>
</template>

<script>
    export default {
    props: ['chats','userid','adminid', 'onlineuserss'],
}

$(document).ready(function(){
var myDiv = $("#myDiv");
myDiv.animate({ scrollTop: myDiv.prop("scrollHeight") - myDiv.height() }, 3000);
});

</script>

【问题讨论】:

  • 为什么要添加laravel标签?

标签: javascript jquery vue.js vue-component


【解决方案1】:

你可以使用这段代码,它应该让你保持在 div 的底部而不是溢出:auto。

var chatWindow = document.getElementById("chat in chats");
    chatWindow.scrollTop = chatWindow.scrollHeight;

【讨论】:

【解决方案2】:
  scrollToEnd () {
      var container = this.$el.querySelector('#myDiv')
      container.scrollTop = container.scrollHeight
  }

【讨论】:

    【解决方案3】:

    您想为滚动元素指定一个 ID,以便您可以轻松选择它。 然后我们希望在数据更新时将该对象的 scrollTop 值设置为等于 scrollHeight。在 vue 中,我们可以通过在数据更新后调用 nextTick() 来做到这一点。

    但是,当我们只这样做时,聊天会在每条新消息上不断向下滚动,这通常不是您想要的,因为这意味着当您的用户向上滚动时,聊天会随着每条新消息不断向下滚动。为了让聊天只在我们已经滚动到底部时向下滚动,我们可以检查用户是否向上滚动,只有在没有滚动的情况下,我们才会自动向下滚动。最终代码如下所示,在更新数据后,您必须在更新数据的函数中执行此操作。

    var chatWindow = document.getElementById('chat-id-here')
    var isScrolled = (chatWindow.scrollTop < chatWindow.scrollHeight - chatWindow.offsetHeight - 10)
    
    Vue.nextTick(function () {
      if (!isScrolled) {
        chatWindow.scrollTop = chatWindow.scrollHeight
      }
    })
    

    请注意,“isScrolled”变量中的“- 10”是在我们停止自动滚动之前用户必须向上滚动的像素数量,因此您可以根据需要进行调整。

    【讨论】:

    • 我收到此错误 - 未捕获的类型错误:无法读取属性 'scrollTop' of null
    • 你给滚动的div一个id属性了吗?如果元素没有 id,我们无法使用 document.getElementById() 选择元素。
    • 我添加了 window.onload 并没有显示任何错误,但滚动仍然在 div 的顶部。
    • 由于您使用的是 Vue,因此您需要将 javascript 代码放入 Vue 组件中。 Vue 组件有自己的位置来存放组件初始化时需要加载的代码。 window.onload 和 document.ready() 仅适用于初始页面加载。但在那之后,页面就再也没有真正加载过,它只是 Vue 动态更新了 DOM 中的所有元素。 Vue 有一些很棒的文档,你可以在这里查看:vuejs.org/v2/guide
    猜你喜欢
    • 2011-02-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多