2017-08-12 77 views

回答

0

我明白了! 對於仍然有麻煩的人: 1.將div溢出爲無 2.給div一個高度和寬度 3.上面的代碼 它將工作。

0

滾動事件不包含關於滾動方向/軸的信息,但實際滾動位置總是作爲可滾動容器的屬性存儲。您必須將某個值緩存到某個位置(例如直接在元素上使用$ .data()),並在滾動時將其與新滾動位置進行比較。當您要求進行垂直滾動時,您必須檢查scrollTop - 屬性,對於水平滾動,請使用scrollLeft

$('#scrollDiv').on('scroll', function(e){ 

    var target = $(e.target); 

    if(target.data('stored_scroll_top') == 'undefined') { 
     target.data('stored_scroll_top', 0); 
    } 

    if (target.data('stored_scroll_top') != e.target.scrollTop) { 
     alert('hi'); 
     target.data('stored_scroll_top', e.target.scrollTop); 
    } 
}); 
0

你可以向你的DIV添加其他兩個數據屬性:

  • 水平:以前scrollLeft價值
  • 垂直:以前scrollTop的值

在滾動您可以比較這些值並決定發生哪個滾動。

以這種方式你也知道滾動的數量。相反,如果您只關心發生了哪種情況,則可能只使用一個變量。

的片段:

$("#scrollDiv").data('horizontal', 0).data('vertical', 0).on('scroll', function (e) { 
 
    var horizontal = $(this).data('horizontal'); 
 
    var vertical = $(this).data('vertical'); 
 
    var cHorizontal = this.scrollLeft; 
 
    var cVertical = this.scrollTop; 
 
    $(this).data('horizontal', cHorizontal); 
 
    $(this).data('vertical', cVertical); 
 
    if (horizontal != cHorizontal) { 
 
     console.log('Horizontal scroll.....'); 
 
    } 
 
    if (vertical != cVertical) { 
 
     console.log('Vertical scroll.....'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div id="scrollDiv" style="overflow: scroll; width: 200px;height: 200px;white-space: nowrap;"> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
    This is a div element.......................................<br/> 
 
</div>