【问题标题】:Use scrollIntoView() and scroll to the bottom of the selected element使用 scrollIntoView() 并滚动到所选元素的底部
【发布时间】:2021-01-15 18:52:25
【问题描述】:

我在 div 中有一个聊天消息列表,并且希望每次添加元素时都滚动到底部。我尝试调用一个选择最后一项并使用scrollIntoView()的函数。

scrollToElement:function() {
   const el = this.$el.getElementsByClassName('message');
    if (el) {
       el[el.length-1].scrollIntoView({behavior: "smooth"});
     }
}

问题在于它滚动到所选元素的顶部,而不是滚动到底部,这是将整个元素包含在视图中所必需的。
我预计:

我得到:

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    每次您将新的聊天消息附加到聊天容器时 - 您都需要将聊天容器滚动到其底部边缘。你可以通过一个简单的分配来做到这一点:

    this.$refs.chatContainer.scrollTop = this.$refs.chatContainer.scrollHeight;
    

    请注意,滚动必须在$nextTick 内部执行,以确保新的聊天消息已添加到 DOM。

    我的建议是在聊天容器上使用 Vue 指令,每次添加新的聊天消息时它都会自动滚动到底部:

      function scrollToBottom(el)
      {
        el.scrollTop = el.scrollHeight;
      }
    
      // Monitors an element and scrolls to the bottom if a new child is added 
      // (always:false = prevent scrolling if user manually scrolled up)
      // <div class="messages" v-chat-scroll="{always: false}">
      //   <div class="message" v-for="msg in messages">{{ msg }}</div>
      // </div>
      Vue.directive('chat-scroll',
      {
        bind: function(el, binding)
        {
          var timeout, scrolled = false;
    
          el.addEventListener('scroll', function(e)
          {
            if (timeout) window.clearTimeout(timeout);
            timeout = window.setTimeout(function()
            {
              scrolled = el.scrollTop + el.clientHeight + 1 < el.scrollHeight;
            }, 200);
          });
    
          (new MutationObserver(function(e)
          {
            var config = binding.value || {};
            var pause = config.always === false && scrolled;
            if (pause || e[e.length - 1].addedNodes.length != 1) return;
            scrollToBottom(el);
          })).observe(el, {childList: true});
        },
        inserted: scrollToBottom
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2019-11-14
      相关资源
      最近更新 更多