简体   繁体   中英

Javascript scroll to element on scroll

I searched very long but haven't found a soulution yet.

I want to scroll to the next element on scroll.

$(window).load(function(){

  var scroll = false;

  $(function() {
    //Create an Array
    var sites = $('.site');
    var position = 0; //Start Position
    var next = $('#next');
    var lastScrollTop = 0;

    $(window).scroll(function(event){
      if(scroll == false){
            scroll = true;
            $(document).off('scroll');
            var st = $(this).scrollTop();
            if (st > lastScrollTop){
              if (position !== sites.length - 1) {
                scrollToPosition(sites[position += 1]),5000;
              }
            } else {
              if (position !== 0) {
                scrollToPosition(sites[position -= 1]),5000;
              }
            }
            lastScrollTop = st;
          }
        });
      })

    function scrollToPosition(element) {
      if (element !== undefined) {
        scrollToElement($(element).attr('id'));
      }
    }

    function scrollToElement(selector, time, verticalOffset) {
      time = typeof(time) != 'undefined' ? time : 500;
      verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
      selector = "#" + selector;
      var element = $(selector);
      offset = element.offset();
      offsetTop = offset.top + verticalOffset;
      $('html, body').animate({
        scrollTop: offsetTop
      }, time);
      scroll = false;
    }
  });

the html has many of these with different ids

<div id="test" style="width:100%; height:100vh;" class="site">

</div>

So the containers are fullscreen hight. and when the user scrolls a bit he should get to the next container. At the moment it scrolls till the end and or more.

It would help if you could create an example in jsFiddle or CodePen, but the first thing I would do is stop any current jQuery animations before launching new ones:

$('html, body').stop().animate({
  scrollTop: offsetTop
}, time);

You should keep in mind that scroll handler is executed many times when user is scrolling.

Also, unrelated - your scrollToPosition calls have brackets at the wrong place and should probably be like this:

scrollToPosition(sites[position += 1], 5000);

Edit:

Another thing that might cause problems - you should unset the 'scroll' flag/variable only when the animation has finished, something like this:

$('html, body').stop().animate({
  scrollTop: offsetTop
}, time, function () {
    scroll = false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM