Synchronized scrolling using jQuery?

后端 未结 8 1234
你的背包
你的背包 2020-11-28 09:29

I am trying to implement synchronized scrolling for two DIV with the following code.

DEMO

$(document).ready(function() {
    $(\"#div1\"         


        
8条回答
  •  盖世英雄少女心
    2020-11-28 09:50

    If you don't want proportional scrolling, but rather to scroll an equal amount of pixels on each field, you could add the value of change to the current value of the field you're binding the scroll-event to.

    Let's say that #left is the small field, and #right is the bigger field.

    var oldRst = 0;
    
    $('#right').on('scroll', function () {
        l = $('#left');
        var lst = l.scrollTop();
        var rst = $(this).scrollTop();
    
        l.scrollTop(lst+(rst-oldRst)); // <-- like this
    
        oldRst = rst;
    });
    

    https://jsfiddle.net/vuvgc0a8/1/

    By adding the value of change, and not just setting it equal to #right's scrollTop(), you can scroll up or down in the small field, regardless of its scrollTop() being less than the bigger field. An example of this is a user page on Facebook.

    This is what I needed when I came here, so I thought I'd share.

提交回复
热议问题