Synchronized scrolling using jQuery?

后端 未结 8 1214
你的背包
你的背包 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 10:10

    From the pawel solution (first answer).

    For the horizzontal synchronized scrolling using jQuery this is the solution:

    var $divs = $('#div1, #div2'); //only 2 divs
    var sync = function(e){
        var $other = $divs.not(this).off('scroll');
        var other = $other.get(0);
        var percentage = this.scrollLeft / (this.scrollWidth - this.offsetWidth);
        other.scrollLeft = percentage * (other.scrollWidth - other.offsetWidth);
        setTimeout( function(){ $other.on('scroll', sync ); },10);
    }
    
    $divs.on('scroll', sync);
    

    JSFiddle

    An other solution for multiple horizontally synchronized divs is this, but it works for divs with same width.

    var $divs = $('#div1, #div2, #div3'); //multiple divs
    var sync = function (e) {
        var me = $(this);
        var $other = $divs.not(me).off('scroll');
        $divs.not(me).each(function (index) {
            $(this).scrollLeft(me.scrollLeft());
        });
        setTimeout(function () {
            $other.on('scroll', sync);
        }, 10);
    }
    $divs.on('scroll', sync);
    

    NB: Only for divs with same width

    JSFiddle

提交回复
热议问题