【发布时间】:2016-05-28 09:58:41
【问题描述】:
我有 4 个高度设置为窗口高度的 div。我希望在每次向下滚动时滚动到下一个,但是在第一次向下滚动之后它只是继续滚动,似乎忽略了is:animated
<style>
.div {
width: 100%;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
.blue {
background: blue;
}
</style>
<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>
function setHeights() {
$('.nbhd').css('height', window.innerHeight);
}
function scrollSections() {
if ($('body, html').is(':animated')) {
return;
}
var currentSectionId = $('.nbhd.scrolledto').data('id');
currentSectionId++;
$('.scrolledto').removeClass('scrolledto');
var section = $('#id'+currentSectionId);
section.addClass('scrolledto');
var pos = section.offset().top;
$('body, html').animate({scrollTop: pos}, 1000, function() {
console.log('animated');
});
}
setHeights();
$( window ).on( "scroll", function() {
scrollSections();
});
小提琴:https://jsfiddle.net/2d47k6af/
由于某种原因,我还收到了 6 次 animated 记录,我预计是 3 次。
【问题讨论】:
-
您已记录了 6 次
animated,因为body记录了 3 次,html记录了 3 次 -
哦,谢谢。
-
您可以使用全局变量来解决您的问题:在脚本顶部定义
var isAnimated = false;;$(window).on('scroll')时设置为真;并在$('html, body').animate()的回调中将其重置为false -
不起作用,如果我这样做,它甚至不会一开始就触发。
标签: javascript jquery