【发布时间】:2015-11-01 13:16:49
【问题描述】:
我希望能够在向下滚动时直接转到下一个 div,在向上滚动时直接转到上一个 div。 这是我的文件,其中包含两个 div 的示例:
$(document).ready(function() {
var lastScrollTop = 0;
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('html, body').animate({
scrollTop: $("#space_od").offset().top
}, 500);
} else {
$('html, body').animate({
scrollTop: $("#black_hole").offset().top
}, 500);
}
lastScrollTop = st;
});
});
body {
padding: 0;
margin: 0;
}
#black_hole {
background-image: url("black_hole.jpg");
background-position: center;
display: block;
height: 100vh;
width: 100%;
}
#space_od {
background-image: url("2001.png");
background-position: center;
display: block;
height: 100vh;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="black_hole">
</div>
<div id="space_od">
</div>
第一次向下滚动时似乎可以正常工作,但向上滚动时却不行,它似乎移动了几个像素然后停止了。有什么想法吗?
【问题讨论】:
-
我不得不多次这样做,但从未见过简洁的实现。这个库对我来说很好用:github.com/zynga/scroller。这个github.com/peachananr/onepage-scroll 在 GitHub 上也很受欢迎,但我不太喜欢这个 API。
-
小提琴示例:jsfiddle.net/r3x7r/410
标签: javascript jquery html css scroll