Jquery scroll of distinguishes between horizontal and vertical scrollbars

  • 2020-03-30 02:35:18
  • OfStack

Jquery in the scroll() event, I want to determine whether the current scroll bar horizontal or vertical;
I started to use the global variable to record the value of the scrollTop, and if it doesn't change then it's scrolling sideways,
But if you have multiple scrollbars on your page, you need multiple global variables to control them.
Scroll jquery distinguishes between horizontal and vertical scrollbars

Solutions:
Each sets the scrollLeft/scrollTop of the selected object once, then binds the scroll event, and when triggered, gets the scrollLeft/scrollTop and the initialized scrollLeft/scrollTop to determine whether it is horizontal or vertical, and updates the scrollLeft/scrollTop stored in the object


<style>
.c{height:120px;width:120px;overflow:auto;border:solid 1px black;margin-bottom:5px;}
</style>
<div class="c">111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111</div>
<div class="c">111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111</div>
<div class="c">111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111</div>
<div class="c">111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111<br>1111111111111111111</div>

<script src="/js/jquery.js"></script>
<script>
$('div').each(function(){$(this).data('slt',{sl:this.scrollLeft,st:this.scrollTop});}).scroll(function(){
    var sl=this.scrollLeft,st=this.scrollTop,d=$(this).data('slt');
    if(sl!=d.sl)alert(' Horizontal scroll ');
    if(st!=d.st)alert(' Vertical scroll ');
    $(this).data('slt',{sl:sl,st:st});///
})
</script>


Related articles: