Recently, I have been working on a live broadcast page, which has a function to realize real-time scrolling of comments. The specific effect is shown in the picture below

General train of thought

  • Get the DOM, and ref is recommended in Vue
  • Element scrollTop = element.scrollheight;

Element. The scrollTop added

The element. scrollTop property gets or sets the number of pixels that an Element’s content scrolls vertically.

An element’s scrollTop value is a measure of the distance from the top of the element’s content (rolled up) to its viewport’s visible content (top). When the content of an element does not produce a vertical scroll bar, its scrollTop value is 0.

Element. ScrollHeight added

The element. scrollHeight read-only property is a measure of the height of an Element’s content, including content that is not visible in the view due to overflow.

The value of scrollHeight is equal to the minimum height that the element needs to fit into the content used in the viewport without the use of scroll bars. Without the vertical scroll bar, the scrollHeight is the same as the clientHeight minimum that the element view needs to fill everything. The padding of the element is included, but the border and margin are not. ScrollHeight also includes pseudo-elements like ::before and ::after.

For a more detailed introduction, please refer to MDN at developer.mozilla.org/zh-CN/docs/…

Specific code

html

<div class="tabs danmuBox" ref="scrolldIV"> <div v-for="item in danmuList" :key="item.id" class="item"> <div class="left"> A </div> <div class="right"> <div class="author"> {{ item.author }} </div> <div class="text" >{{ item.text  }}</div> </div> </div> </div>Copy the code

js


let div = this.$refs.scrolldIV
this.$nextTick(() => {
  div.$el.scrollTop = div.$el.scrollHeight;
})
Copy the code

data

 danmuList: [
        {
          id: 1,
          text: "AAAAAA",
          author: "wb_zhhh",
          color:'f5f5f5'
        },
        {
          id: 2,
          text: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaa",
          author: "wb_zhhhAAAAAAAAAAAAAAAAAAAAAAAAa",
          color:'999999'
        },
        {
          id: 3,
          text: "AAAAAA",
          author: "wb_zhhh",
          color:'666666'
        },
      ],
Copy the code

Use case

Hello, everyone, I am [Zhang Xiaoyi], welcome to follow my public account (front-end ZML), learn and communicate together