简体   繁体   English

Javascript滚动到滚动元素

[英]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 html中有许多具有不同ID的

<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: 如果可以在jsFiddle或CodePen中创建示例,这会有所帮助,但是我要做的第一件事是在启动新的jQuery动画之前停止所有当前的jQuery动画:

$('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调用在错误的位置带有括号,并且可能应该像这样:

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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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