简体   繁体   English

jQuery autoScroll 到最近的部分

[英]jQuery autoScroll to the nearest section

If the user is place in the top half of current section it automatically scroll top of that section.如果用户位于当前部分的上半部分,它会自动滚动该部分的顶部。

Then if the user is in the bottom half of the current section it automatically scroll to the top next section.然后,如果用户在当前部分的下半部分,它会自动滚动到下一部分的顶部。

function autoScroll(aid){
    var aTag = $("#"+ aid);
    body.animate({scrollTop: aTag.offset().top},1500);
} 

$(window).scroll(function() {
      var windowScroll = $(window).scrollTop();
      if(windowScroll < ($("#Section2").offset().top/2) && !(windowScroll > ($("#Section2").offset().top/2))){
                    section_id = 'Section1';
        }
        $(document).off('scroll');
        console.log(section_id);
        autoScroll(section_id);
});

http://jsfiddle.net/x6xzh69v/2/ http://jsfiddle.net/x6xzh69v/2/

I created a working example in CODEPEN .我在CODEPEN 中创建了一个工作示例。

 $(document).ready(function() { var origHeight = []; var curScroll = 0; var cumSumHeight = 0; var animHeight = 0; var i = 0; var timeoutVar; $(".section").each(function(index) { origHeight.push($(this).height()); }); $(window).scroll(function() { curScroll = $("body").scrollTop(); cumSumHeight = 0; while ((cumSumHeight + origHeight[i]) < curScroll) { cumSumHeight += origHeight[i]; i++; } if (i == 0) { if (curScroll < (origHeight[i] / 2)) { animHeight = 0; } else { animHeight = origHeight[i]; } } else { if ((curScroll - cumSumHeight) < (origHeight[i] / 2)) { animHeight = cumSumHeight; } else { animHeight = origHeight[i] + cumSumHeight; } } clearTimeout(timeoutVar); timeoutVar = setTimeout(function() { $("body").stop(true,true).animate({ scrollTop: animHeight }, 200); }, 300); }); });
 .section { width: 100%; position: relative; height: 300px; } #Section1 { background: red; } #Section2 { background: blue; } #Section3 { background: orange; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section id="Section1" class="section"></section> <section id="Section2" class="section"></section> <section id="Section3" class="section"></section>

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

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