慕村225694
如果 jQuery 是一个选项,那将是具有最佳浏览器兼容性的最简单的解决方案。您可以使用“wheel”事件侦听器来检测滚动的方向,然后使用 jQuery animate 将窗口滚动到相应的元素。我提供了一个基于此 GitHub 存储库的示例:https ://github.com/epranka/sections-slider 。(function($) { var selector = ".section"; var direction; var $slide; var offsetTop; var $slides = $(selector); var currentSlide = 0; var isAnimating = false; var stopAnimation = function() { setTimeout(function() { isAnimating = false; }, 300); }; var bottomIsReached = function($elem) { var rect = $elem[0].getBoundingClientRect(); return rect.bottom <= $(window).height(); }; var topIsReached = function($elem) { var rect = $elem[0].getBoundingClientRect(); return rect.top >= 0; }; document.addEventListener( "wheel", function(event) { var $currentSlide = $($slides[currentSlide]); if (isAnimating) { event.preventDefault(); return; } direction = -event.deltaY; if (direction < 0) { // next if (currentSlide + 1 >= $slides.length) { return; } if (!bottomIsReached($currentSlide)) { return; } event.preventDefault(); currentSlide++; $slide = $($slides[currentSlide]); offsetTop = $slide.offset().top; isAnimating = true; $("html, body").animate({ scrollTop: offsetTop }, 1000, stopAnimation ); } else { // back if (currentSlide - 1 < 0) { return; } if (!topIsReached($currentSlide)) { return; } event.preventDefault(); currentSlide--; $slide = $($slides[currentSlide]); offsetTop = $slide.offset().top; isAnimating = true; $("html, body").animate({ scrollTop: offsetTop }, 1000, stopAnimation ); } }, { passive: false } );})(jQuery);.section { position: relative; display: flex; height: 100vh;}#section1 { background: blue;}#section2 { background: #ff8c42;}#section3 { background: #6699cc;}#section4 { background: #00b9ae;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="section1" class="section"></div><div id="section2" class="section"></div><div id="section3" class="section"></div><div id="section4" class="section"></div>