Synchronized scrolling using jQuery?

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

    You can use element.scrollTop / (element.scrollHeight - element.offsetHeight) to get the percentage (it'll be a value between 0 and 1). So you can multiply the other element's (.scrollHeight - .offsetHeight) by this value for proportional scrolling.

    To avoid triggering the listeners in a loop you could temporarily unbind the listener, set the scrollTop and rebind again.

    var $divs = $('#div1, #div2');
    var sync = function(e){
        var $other = $divs.not(this).off('scroll'), other = $other.get(0);
        var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
        other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
        // Firefox workaround. Rebinding without delay isn't enough.
        setTimeout( function(){ $other.on('scroll', sync ); },10);
    }
    $divs.on( 'scroll', sync);
    

    http://jsfiddle.net/b75KZ/5/

提交回复
热议问题