Scroll 2 scrollbars with jquery the same time

后端 未结 4 1656
心在旅途
心在旅途 2020-12-09 04:59

Is it possible to scroll 2 scrollbars with one scrollbar?

相关标签:
4条回答
  • 2020-12-09 05:20

    I want to add a little improvement to the solution of beeglebug (which is already working nearly perfect).

    If you discover VERY SLOW SCROLLING by using the MOUSEWHEEL on some browsers (e.g. OPERA), try to use unique IDs for the DIVs instead of the class:

    $('#master').scroll(function(){
    $('#slave').scrollTop($(this).scrollTop());
    }); 
    

    I had this problem and tried many solution but this one finally was the easiest. Taking a wild guess, i would claim that OPERA gets some performance problems while identifying the DIVs by class all the time when scrolling. (just noticed massive raise in CPU usage while using class as identifier)

    0 讨论(0)
  • 2020-12-09 05:24

    (to append beeglebug):

    For horizontal 'linked' scrolling use:

    $('.linked').scroll(function(){
        $('.linked').scrollLeft($(this).scrollLeft());
    });
    
    0 讨论(0)
  • 2020-12-09 05:25

    All you need to do it tie the scrollTop property of one element to the scrollTop of the other, using a function tied to the scroll event.

    Something along the lines of:

    $('.linked').scroll(function(){
        $('.linked').scrollTop($(this).scrollTop());    
    })
    

    With that function, all elements with a class of linked will scroll whenever you use the scrollbars of one of them. (I assumed vertical scrolling, if you wanted horizontal, do the same but with scrollLeft)

    See http://jsfiddle.net/g8Krz/510/ for a working example of the above.

    0 讨论(0)
  • 2020-12-09 05:36

    If you are experiencing slow scrolling when you are using your mousewheel on linking scrollbars with beeglebug solution, here is a trick to fix it.

    The cool thing is that it is kinda compact and it doesn't use any id, only classes, so much more sustainable.

    // First add the class "linked-scrollbar" to the elements you want to link
    
    // Then manually or dynamically add an attribute which will contain
    // the data if the element is currently scrolling or not
    $('.linked-scrollbar').attr("data-scrolling", "false");
    
    $('.linked-scrollbar').scroll(function(){
        if($(this).attr("data-scrolling") == "false"){
            $('.linked-scrollbar').not(this).attr("data-scrolling", "true");
            $('.linked-scrollbar').not(this).scrollLeft($(this).scrollLeft());
        }
        $(this).attr("data-scrolling", "false");
    });
    

    Here is a jsfiddle showing that bug and the fix.

    0 讨论(0)
提交回复
热议问题