background

Overflow :scroll is set when the content height exceeds the container height and the container sets overflow:scroll; The scroll bar appears, but may be hidden on the mobile side. However, some scenarios do need the prompt function of the scroll bar. For example, the following figure requires the user to input some information. If there is no scroll bar, the user will not know that there are untyped items causing information leakage.

Effect preview

How do you implement a scrollbar? We need to implement several things:

  1. The scroll bar consists of a track and a slider
  2. Proportion of slider height to track = total visible height of container/container sliding height
  3. The slider moves smoothly as the slide moves

Train of thought

1. Calculate the proportion of the slider height to the track

The sliding height of the container can be obtained using scrolldom.scrollheight

The container visual height is obtained using getComputedStyle(scrollDom).height

Note that dom.style.height does not get the height set by CSS

2. Move the slider as the content scrolls

Use Windows. RequestAnimationFrame in every rendering update the position of the slider, sliding effect will be more smooth. Calculate the proportion of the slider that should slide using the scrollTop property.

function getMove(selector) {
    return function move() {
      // The container can slide height
      var scrollHeight = document.querySelector(selector).scrollHeight;
      // Visual height of container
      var domHeight = getComputedStyle(document.querySelector(selector)).height;
      domHeight = parseFloat(domHeight.substring(0, domHeight.length - 2));
      // Orbit height
      var barHeight = getComputedStyle(document.querySelector(".scrollBar")).height;
      barHeight = parseFloat(barHeight.substring(0, barHeight.length - 2));
      
      // scrollTop
      var offsetY = document.querySelector(selector).scrollTop;
      
      // Update the slider position
      document.querySelector(".thumb").style.top = (barHeight * offsetY) / scrollHeight + "px";
      
      // Call requestAnimationFrame recursively
      window.requestAnimationFrame(getMove(selector));
    };
}
window.requestAnimationFrame(getMove(".remark_list"));
Copy the code

The complete code

The complete code