gpt4 book ai didi

javascript - 在滚动顶部动画时防止硬滚动时晃动

转载 作者:行者123 更新时间:2023-12-01 05:30:44 25 4
gpt4 key购买 nike

我正在逐节滚动,但如果我用鼠标猛烈滚动(不仅仅是一次简单的滚动)或在笔记本电脑触摸板上猛烈滚动,它会在滚动动画开始之前上下晃动,甚至跳两段!

是否可以让它平滑地滚动,并且始终只滚动一个部分(而不是跳2个部分),无论某人滚动有多努力,并且在动画发生时基本上禁用滚动?

我的代码(JSFiddle):

var isAnimated = false;
var nbhdLength = $('.nbhd').length;
var lastSectionId = nbhdLength - 1;
var allHeight = (nbhdLength - 1) * window.innerHeight;
var up = true;

function setHeights() {
$('.nbhd').css('height', window.innerHeight);
}

setHeights();

$('html').mousewheel(function(e) {

var up = e.deltaY > 0;

if (up) {
console.log('up');
up = true;

} else {
console.log('down');
up = false;
// console.log(up);
}


if (!up && $('#id' + lastSectionId).hasClass('scrolledto') || (!up && !$('.scrolledto').length)) {
$('.scrolledto').removeClass('scrolledto');
return;
}

if (isAnimated) return;
isAnimated = true;

var currentSectionId = $('.nbhd.scrolledto').data('id');

up ? currentSectionId-- : currentSectionId++;

if (currentSectionId < 0) currentSectionId = 0;

if (!$('.scrolledto').length) currentSectionId = lastSectionId;

$('.scrolledto').removeClass('scrolledto');

var section = $('#id' + currentSectionId);

section.addClass('scrolledto');

var pos = section.offset().top;

$('body, html').animate({
scrollTop: pos
}, 1000, function() {
setTimeout(function() {
isAnimated = false;
}, 100)
console.log($(window).scrollTop());
});

});
.div {
width: 100%;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
.blue {
background: blue;
}
.abovefooter {
background: gray;
height: 200px;
}
.footer {
background: black;
height: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>


<div id="id0" data-id="0" class="nbhd red scrolledto"></div>
<div id="id1" data-id="1" class="nbhd yellow"></div>
<div id="id2" data-id="2" class="nbhd green"></div>
<div id="id3" data-id="3" class="nbhd blue"></div>
<div class="abovefooter"></div>
<div class="footer"></div>

最佳答案

您需要防止默认的 mouseWheel 事件发生,而是使用 JavaScript 来执行所需的效果。

$('html').mousewheel(function(e) {
e.preventDefault();
//...
}

演示:https://jsfiddle.net/b67uw0cx/1/

关于javascript - 在滚动顶部动画时防止硬滚动时晃动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37504452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com