Custom Scrollbar Maths in jQuery / JavaScript

2020-03-27 01:32发布

问题:

I am currently working on a project which uses a custom scroll plugin (written by me) to allow an element to be scrolled in touch devices, as well as desktop browsers. Everything is working correctly (including velocity and deceleration a la iOS).

However, the only problem that remains is calculating the top (or left) position of the scrollbar when a user scrolls. I have calculated the height of the scrollbar with the following formular:

Math.round((container.height() / content.height()) * 100);

This seems to compute the correct height of the bar, but now I need a formular to work out by how much the scrollbar's position should be moved when the user scrolls. I have checked through Google and wasn't able to find much of use, and also searched here on SO and would welcome any comments.

I have the following data available for use in the formula:

  • Container height
  • Content height
  • Current scroll position (scrollTop)
  • Height of scrollbar

回答1:

position of the scrollbar should be calculated by this formula:

Math.round((scrollbar.height * scrollTop / content.height());