我遇到了一个问题,需要您的指导。当我结束在页面上滚动(鼠标滚轮和触控板)时,我愿意执行动画。
当我停止滚动时,窗口应该捕捉到最近的元素,并且仅当窗口顶部距离该元素小于 100px 时才如此。
我尝试过使用任何插件,例如 fullpage.js、snapscroll 和 skrollr,它们的核心包中集成了此功能,但是它不符合我的需求,因为它们都没有关于该功能的适当文档。滚动方向或滚动量本身。
我一直在尝试包含上述条件,但没有成功:
- 向上或向下滚动方向
- 捕捉发生的固定金额
这是我的 HTML 结构:
<div class="section" id="section-1">
content here
</div>
<div class="section" id="section-2">
content here
</div>
<div class="section" id="section-3">
content here
</div>
<div class="section" id="section-4">
content here
</div>
这是我到目前为止的 jQuery 脚本:
var items = $(".section");
var animating = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
console.log('We are scrolling down!');
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
animating = true;
$('body').animate({
scrollTop: $(value).offset().top + 'px'
}, 250);
setTimeout(function() {
animating = false;
}, 300);
return true;
});
}, 1200));
};
} else {
console.log('We are scrolling down!');
}
lastScrollTop = st;
});
提前致谢
最佳答案
我希望这就是您正在寻找的
var timeout = 1200;
var timer;
$(window).scroll(function(event){
clearTimeout(timer);
timer = setTimeout(function() {
$(".section").each(function() {
var scrollTop = $(window).scrollTop();
var offset = $(this).offset().top;
if(offset-scrollTop < 100 && offset-scrollTop > -100) {
$('html,body').animate({scrollTop: $(this).offset().top},'slow');
return;
}
});
}, timeout);
});
关于javascript - 仅在向下滚动时捕捉滚动到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871956/