简体   繁体   中英

Autoscroll div issue

I am trying to make a div scroll as content is added into it. I am using a Vuejs list which updates items as source array (a vuejs's data array) changes.

<message v-for="message in messages"></message>

This is my auto-scroll pseudo-code:

let scroll = false;

messagesContainer.addMessageChild(new messageElement(...)); // addMessageChild appends item to vuejs's data, it may be async when it actually adds the element to the DOM which may cause the problem

if (messagesContainer.scrollTop = maxScrollOfMessagesContainer)
    scroll = true;
messagesContainer.scrollTop = maxScrollOfMessagesContainer;

However, the messages container element does not scroll. I fear that Vuejs may update (insert) elements from source (data) asynchronously, this way possibly skipping the if (messagesContainer.scrollTop = maxScrollOfMessagesContainer) check (Adding the element (message) after the check).

What could I possibly do to prevent this?

What about a method to scroll on the last message ?

Template:

<message v-for="message in messages" v-class="last-message : $index === (items.length-1)">
</message >

Methods:

// smooth scroll on .last-message
scrollToLastMessage: function () {
  document.querySelector('.last-message').scrollIntoView({ 
    behavior: 'smooth' 
  })
}

// scroll when messages change
watch: {
  messages: function () {
    this.scrollToLastMessage()
  }
}

// scroll when page ready
ready() {
  this.scrollToLastMessage()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM