简体   繁体   中英

Calculate Scroll Position using vanilla javascript

The wrapper overflows on x direction so it has horizontal scrolling, and the table inside.body overflows on y direction so it has vertical scrolling. The Markup looks like below.

 <div class="container"> <div class="wrapper"> <div class="head"> <table>...</table> </div> <div class="body"> <table>...</table> </div> </div> </div>

I've removed the default browser scrollbars and created custom scrollbars . The custom scrollbars are created for the container element. When wrapper scrolls horizontally then container's x-scrollbar scrolls, and when table inside body scrolls vertically then container's y-scrollbar scrolls.

The problem is with the vertical scrollbar. When I click and drag and the vertical scrollbar's thumb, I've to update the scrollTop of the table inside body. I'm founding it hard to figure out the right calculations to update the scrollTop .? Someone help me fix this.

I've set up the mousedown , mousemove and mouseup listeners for the y-scrollbar's thumb to calculate the amount of distance dragged, but how do I calculate the scrollTop of the table inside body with respect to the amount of distance dragged in the y-scrollbar ?

I figured out the correct calculations.

var elem = document.querySelector('.body table'); // Content to be scrolled.
var yTrack = document.querySelector('.track.y'); // scroll-track-y
var yBar = yTrack.querySelector('.bar'); // scroll-thumb-y

On mousedown event, I'm setting the intial values to an object. On mousemove event, I'm updating the scrollTop of the element to be scrolled. Then on mouseup event i'm setting that object to null.

function yBar_OnMouseDown(e)
{
    initCoords = {
        axis: 'y',
        abs: e.pageY,
        bar: yBar,
        p0: yBar.offsetTop
    };
};

function yBar_OnMouseMove(e)
{
    if (initCoords && initCoords.axis === 'y')
    {
        var maxElemScroll = elem.scrollHeight - elem.clientHeight;
        var room = yTrack.scrollHeight - yBar.clientHeight;
        var diff = e.pageY - initCoords.abs;
        var abs = initCoords.p0 + diff;
        var maxTrackScroll = yTrack.offsetHeight - yBar.offsetHeight;

        abs = abs < 0 ? 0 : maxTrackScroll < abs ? maxTrackScroll : abs;
        elem.scrollTop = maxElemScroll * abs / room;
    }
};

function yBar_OnMouseUp(e)
{
    initCoords = null;
};

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