How do I scroll a column at a different speed?

2019-04-08 04:27发布

问题:

I have two columns, #photos and #text. My #photos column is longer and logically holds some images. When I scroll the page, I like the #photos column to scroll faster than the #text column, so that both columns align at the bottom.

I use jQuery's $(window).scroll() to update the #photos column:

$("#photos").css("top", Math.round(targetY));

How do I calculate targetY?

I know it probably has something to do with $(document).height(), $("#photos").height() and $(window).scrollTop(), but I can't figure out the formula.

回答1:

Without a bit more code to look at, I can't really suggest changes to make directly to your code but I've managed to mock up a working version of what you're perhaps looking for with the following jsFiddle.

I've also broken down the equation into parts to make it easier to see what's going on.

So as you scroll the text div, the photos div scrolls at the same ratio depending on the height of the two containers.

JavaScript:

$(document).ready(function(){
    $('#textScroll').scroll(function(){
        var textDiff = $('#text').height() - $('#textScroll').height();
        var textDiffRatio = (1 / textDiff) * $('#textScroll').scrollTop();
        var photosDiff = $('#photos').height() - $('#photosScroll').height();
        var photosScrollTop = textDiffRatio * photosDiff;
        $('#photosScroll').scrollTop(photosScrollTop);
    });
});

HTML:

<div id="textScroll" style="width:100px; height:100px; overflow:auto;">
    <div id="text">
        Text 1<br />
        Text 2<br />
        Text 3<br />
        Text 4<br />
        Text 5<br />
        Text 6<br />
        Text 7
    </div>
</div>
<div id="photosScroll" style="width:100px; height:100px; overflow:auto;">    
    <div id="photos">
        Photos 1<br />
        Photos 1<br />
        Photos 2<br />
        Photos 2<br />
        Photos 3<br />
        Photos 3<br />
        Photos 4<br />
        Photos 4<br />
        Photos 5<br />
        Photos 5<br />
        Photos 6<br />
        Photos 6<br />
        Photos 7<br />
        Photos 7
    </div>
</div>

Hope it helps you solve your problem.