Synchronized scrolling using jQuery?

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

    This is what I'm using. Just call the syncScroll(...) function with the two elements you want to synchronize. I found pawel's solution had issues with continuing to slowly scroll after the mouse or trackpad was actually done with the operation.

    See working example here.

    // Sync up our elements.
    syncScroll($('.scroll-elem-1'), $('.scroll-elem-2'));
    
    
    /***
    *   Synchronize Scroll
    *   Synchronizes the vertical scrolling of two elements.
    *   The elements can have different content heights.
    *
    *   @param $el1 {Object}
    *       Native DOM element or jQuery selector.
    *       First element to sync.
    *   @param $el2 {Object}
    *       Native DOM element or jQuery selector.
    *       Second element to sync.
    */
    function syncScroll(el1, el2) {
      var $el1 = $(el1);
      var $el2 = $(el2);
    
      // Lets us know when a scroll is organic
      // or forced from the synced element.
      var forcedScroll = false;
    
      // Catch our elements' scroll events and
      // syncronize the related element.
      $el1.scroll(function() { performScroll($el1, $el2); });
      $el2.scroll(function() { performScroll($el2, $el1); });
    
      // Perform the scroll of the synced element
      // based on the scrolled element.
      function performScroll($scrolled, $toScroll) {
        if (forcedScroll) return (forcedScroll = false);
        var percent = ($scrolled.scrollTop() / 
          ($scrolled[0].scrollHeight - $scrolled.outerHeight())) * 100;
        setScrollTopFromPercent($toScroll, percent);
      }
    
      // Scroll to a position in the given
      // element based on a percent.
      function setScrollTopFromPercent($el, percent) {
        var scrollTopPos = (percent / 100) *
          ($el[0].scrollHeight - $el.outerHeight());
        forcedScroll = true;
        $el.scrollTop(scrollTopPos);
      }
    }
    

提交回复
热议问题