滚动进入视图和if语句读取用户滚动单独工作,但不能让他们一起工作。
<script type="text/javascript">
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
window.scrollTo(0,0);
}
else{
console.log('Scroll down');
document.querySelector('#PROJECTS-2').scrollIntoView();
}})
</script>发布于 2021-08-29 00:02:08
解释:当鼠标滚轮向上或向下移动时,if语句触发,该语句检查移动是正还是负。如果值为正,则将“滚动向上”写入控制台,并将用户滚动到页面开始。
如果为负值,则将“滚动向下”写入控制台,并将div存储在变量元素中,变量元素是我要向下滚动的目标。常数y将存储当前滚动的元素+像素的位置,然后window.scroll()将滚动到元素的顶部。
通过调整顶部: y-+,您可以在滚动后设置以像素为单位的填充。
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
window.scrollTo(0,0);
}
else {
console.log('Scroll down');
let element = document.querySelector('#PROJECTS-2');
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
}
})发布于 2021-08-28 19:11:10
我建议您跳过jQuery,只需使用css滚动快照。(只要您不必支持IE11。)
下面是一个简单的例子:
* {
box-sizing: border-box;
}
html {
font-family: sans-serif;
scroll-snap-type: mandatory;
scroll-snap-points-y: repeat(100vh);
scroll-snap-type: y mandatory;
}
section {
border-bottom: 1px solid white;
padding: 1rem;
height: 100vh;
scroll-snap-align: start;
text-align: center;
position: relative;
}
h1 {
position: absolute;
top: 50%;
transform: translateY(-50%);
text-align: center;
color: black;
width: 100%;
left: 0;
font-size: calc(1rem + 3vw);
}<section style="background:red">
<h1>One</h1>
</section>
<section style="background:blue">
<h1>Two</h1>
</section>
<section style="background:green">
<h1>Three</h1>
</section>
<section style="background:yellow">
<h1>Four</h1>
</section>
https://stackoverflow.com/questions/68967171
复制相似问题