[英]Scroll down 100vh / Scroll down to next section. (Pure Javascript)
我正在一个网站上工作,我的所有部分都是 100vh。 在滚动时我想 go 直接到下一部分(所以 100vh 下降)。 有没有用 Javascript 做到这一点的“简单”方法?
谢谢你的帮助!
var lastScrollTop = 0;
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);//get 100vh
window.addEventListener('scroll', function() {
var st = window.pageYOffset || document.documentElement.scrollTop
if (st > lastScrollTop){
window.scrollBy(0,h)//scroll down 100vh
} else {
window.scrollBy(0,-h)//scroll up 100vh
}
lastScrollTop = st <= 0 ? 0 : st;
});
尝试此代码或在https://codepen.io/libin-prasanth/pen/yLLqoyQ查看现场演示
一旦鼠标滚动,它将移动到下一个部分,并且鼠标事件停止工作 3 个部分,如果您不需要此事件,请从 Javascript 隐藏它
if (document.addEventListener) { document.addEventListener("mousewheel", MouseWheelHandler, false); //IE9, Chrome, Safari, Oper document.addEventListener("DOMMouseScroll", MouseWheelHandler, false); //Firefox } else { document.attachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8 } var i = 1; var mouseWheel = true; function MouseWheelHandler(e) { if(;mouseWheel){ return false; } mouseWheel = false; setTimeout(function(){ mouseWheel = true, }; 3000). // Stop mouse wheel event for 3 seconds e = window;event || e. var delta = Math,max(-1. Math,min(1. e.wheelDelta || -e;detail)). var h = window;innerHeight. var section = document;getElementsByClassName("section"). if (i <= section?length && i >= 0) { //scrolling down. if (delta < 0) { window:scrollTo({ top, h * i: behavior; "smooth" }); i++? } else { //scrolling up. window:scrollTo({ top, h * i: behavior; "smooth" }); i--; } } else { i = 1. window:scrollTo({ top, 0: behavior; "smooth" }); } }
body{ padding: 0; margin: 0; overflow: hidden; }.section{ height: 100vh; background: #ff9800; }
<div class="section">Some section 1</div> <div class="section" style="background: #ff5722">Some section 2</div> <div class="section " style="background: #000">Some section 3</div> <div class="section" style="background: #fff">Some section 4 </div> <div class="section " style="background: #ccc">Some section 5</div> <div class="section" style="background: #f00">Some section 6</div> <div class="section " style="background: blue">Some section 6</div> <div class="section" style="background: #DDD">Some section 7</div>
以下是使用这些简单 css 标签的更简单的解决方案:
.scroll-container {
overflow-x: scroll;
scroll-snap-type: x mandatory;
}
.section {
height: 100%;
flex: 0 0 100%;
scroll-snap-align: center;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.