我遇到了一个问题,需要你的指导。我结束在页面上滚动(鼠标滚轮和触控板)时我愿意执行动画。
当我停止滚动时,窗口应该捕捉到最近的元素,并且仅当窗口顶部在元素附近小于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;
});
提前致谢
答案 0 :(得分:4)
我希望这就是你要找的东西
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);
});