1. 程式人生 > >繫結兩個滾動條同時滾動

繫結兩個滾動條同時滾動

瞭解知識背景(使用JQuery):

使用到的方法:

1> sroll()方法:當用戶滾動指定的元素時,會發生 scroll 事件  -->  http://www.w3school.com.cn/jquery/event_scroll.asp

2>srollLeft():返回或設定匹配元素的滾動條的水平位置  -->  http://www.w3school.com.cn/jquery/css_scrollleft.asp

3>scrollTop() ::返回或設定匹配元素的滾動條的垂直位置 --> http://www.w3school.com.cn/jquery/css_scrolltop.asp

示例:

HTML

<div>
  <div class="fixedWidth">
      <div class="A">
        A is here!!!
        
      </div>
  </div>
  
  <div class="fixedWidth">
    <div class="B">
        B is here!!!
    </div>
  </div>  
</div>


CSS程式碼:

.A{
  width:1270px;
  background-color:lightblue;
}

.B{
  width:1270px;
  background-color:yellow;
}

.fixedWidth{
  width: 500px;
  overflow: auto;
}


JS程式碼:

    // 載入滾動條的相互繫結事件 
    //A繫結B
    $(".A").scroll(function(event){
      $(".B").scrollLeft($(this).scrollLeft()); 
      $(".B").scrollTop($(this).scrollTop()); 
    });
    //B繫結A
    $(".B").scroll(function(event) {
      $(".A").scrollLeft( $(this).scrollLeft());
      $(".A").scrollTop( $(this).scrollTop());
    });