Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to detect the end of a horizontal scroll in a div?

I was trying to implement a horizontal scroll inside a div. My question is how can I detect the end of the horizontal scroll?

I tried something like this

$(function() {
var scrollLeftPrev=0;
$('#scrollquestion').scroll( function() {
  var newScrollLeft=$('#scrollquestion').scrollLeft();
  if(scrollLeftPrev===newScrollLeft){
    alert('right end');
  }
  if(newScrollLeft===0){
    alert('left end');
  }
  console.log($('#scrollquestion').width());
  console.log(newScrollLeft);
  scrollLeftPrev=newScrollLeft;
 });
});

left end alert works, since it will become 0 for all the device sizes. For right end, it depends on the device size.

Screen : Horizontal scroll

JS Fiddle : http://jsfiddle.net/arunslb123/trxe4n3u/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use scrollWidth and width along with your leftscrollwidth to get the difference. In your case there is offset of 8 so it will give the difference of 8 it may be because of your padding or margin.

var $elem=$('#scrollquestion');
var newScrollLeft = $elem.scrollLeft(),
    width=$elem.width(),
    scrollWidth=$elem.get(0).scrollWidth;
var offset=8;
if (scrollWidth- newScrollLeft-width==offset) {
    alert('right end');
}

Live Demo

Use the outerWidth() to get the offset including the width like,

var $elem=$('#scrollquestion');
var newScrollLeft = $elem.scrollLeft(),
    width=$elem.outerWidth(),
    scrollWidth=$elem.get(0).scrollWidth;
if (scrollWidth-newScrollLeft==width) {
    alert('right end');
}

Another Demo without using offset


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...