使用一个变量来存储锚列表,然后是当前列表的键索引,如下所示:
$myAnchors = $('.js_anchor');
currentAnchor = -1;
$(document).keydown(function(e){
if (e.keyCode == 40) {
console.log('keydown');
if ($myAnchors.length < currentAnchor+1) {
currentAnchor++;
$(window).animate({scrollTop: $myAnchors.eq(currentAnchor).offset().top}, 2000,'easeInOutCubic');
}
}
});
如果用户自己滚动并按下可能向上滚动的向下箭头,这会产生一些不良影响...使用此函数来确定要滚动到哪个:
function getAnchorOffset(prevnext){
//prevnext = 'next' or 'prev' to decide which we want.
currentPosition = $(window).scrollTop();
for(k in $myAnchors){
if($myAnchors[k].offset().top<currentPosition && $myAnchors[k].offset().top>closestOffset){
closestOffset = $myAnchors[k].offset().top;
key = k;
}else if($myAnchors[k].offset().top>currentPosition){
break;
}
}
if(prevnext=='next'){
return $myAnchors[key+1].offset().top;
}else{
return closestOffset;
}
}
并更换
$(window).animate({scrollTop: $myAnchors.eq(currentAnchor).offset().top}, 2000,'easeInOutCubic');
经过
$(window).animate({scrollTop: getAnchorOffset('next')}, 2000,'easeInOutCubic');
请注意,它尚未经过测试,但应该接近工作,如果还没有工作的话。