Synchronized scrolling using jQuery?

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

    I solved the sync scrolling loop problem by setting the scroll percentage to fixed-point notation: percent.toFixed(0), with 0 as the parameter. This prevents mismatched fractional scrolling heights between the two synced elements, which are constantly trying to "catch up" with each other. This code will let them catch up after at most a single extra step (i.e., the second element may continue to scroll an extra pixel after the user stops scrolling). Not a perfect solution or the most sophisticated, but certainly the simplest I could find.

    var left = document.getElementById('left');
    var right = document.getElementById('right');
    var el2;
    var percentage = function(el) { return (el.scrollTop / (el.scrollHeight - el.offsetHeight)) };
    
    function syncScroll(el1) {
      el1.getAttribute('id') === 'left' ? el2 = right : el2 = left;
      el2.scrollTo( 0, (percentage(el1) * (el2.scrollHeight - el2.offsetHeight)).toFixed(0) ); // toFixed(0) prevents scrolling feedback loop
    }
    
    document.getElementById('left').addEventListener('scroll',function() {
      syncScroll(this);
    });
    document.getElementById('right').addEventListener('scroll',function() {
      syncScroll(this);
    });
    
    

提交回复
热议问题