【发布时间】:2015-11-15 03:31:39
【问题描述】:
我目前有许多可以在下面看到的 div 标签,每个标签都是视口的高度。
<!-- .current represents the div the user is currently viewing -->
<div class="full-height current" id="id1">
<div class="container">
</div>
</div>
<div class="full-height" id="id2">
<div class="container">
</div>
</div>
<div class="full-height" id="id3">
<div class="container">
</div>
</div>
<div class="full-height" id="id4">
<div class="container">
</div>
</div>
<div class="full-height" id="id5">
<div class="container">
</div>
</div>
我正在尝试实现一项功能,在用户滚动时,窗口将滚动到下一个 div 标签,一次始终只有一个 div 视图。我实现它的方式效果很好,除了动画再次触发滚动事件,一旦用户滚动就会导致页面滚动的无限循环。我试图通过设置一个变量来解决此问题,如果动画正在进行,该变量将阻止事件触发,但它似乎不起作用。我知道我不是为向上滚动而这样做的,但我只是想先看看它是否适用于向下滚动。
$(window).scroll(function(event) {
var scrollTop = $(this).scrollTop();
// If user scrolls down
if ((scrollTop > lastScrollTop) && $(".current").next("div").length > 0) {
if (animating == false) {
console.log("down");
$(".current").next("div").addClass("current");
$(".current").first().removeClass("current");
animating = true;
$("html, body").animate({
scrollTop: $(".current").offset().top
}, 1000, function() {animating = false});
}
// If user scrolls up
} else {
if ($(".current").prev("div").length > 0) {
console.log("up");
$(".current").prev("div").addClass("current");
$(".current").last().removeClass("current");
$("html, body").animate({
scrollTop: $(".current").offset().top
}, 1000);
}
}
lastScrollTop = scrollTop;
});
包含 CSS 以防万一。 100vh - 111px 是由于顶部的固定导航栏高 111px
/* Makes the element take up the entire height of the screen */
.full-height{
height: -o-calc(100vh - 111px); /* opera */
height: -webkit-calc(100vh - 111px); /* google, safari */
height: -moz-calc(100vh - 111px); /* firefox */
}
#id1 {
background-color: red;
}
#id2 {
background-color: blue;
}
#id3 {
background-color: yellow;
}
#id4 {
background-color: green;
}
#id5 {
background-color: purple;
}
如果有人能给我解决我的问题的任何想法,那就太好了。
【问题讨论】:
-
没有
.current元素出现在html上? -
@guest271314 不确定你的意思
-
htmlat Question 似乎不包含具有class.current的元素,在scroll事件处理程序中引用了该元素 -
第一个div标签包含一个.current类
-
是的,你是对的。
lastScrollTop在初始滚动时会是undefined吗?
标签: javascript jquery html css scroll