Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用键盘和jQuery从一个锚点到另一个锚点的动画滚动_Jquery_Scroll_Anchor - Fatal编程技术网

使用键盘和jQuery从一个锚点到另一个锚点的动画滚动

使用键盘和jQuery从一个锚点到另一个锚点的动画滚动,jquery,scroll,anchor,Jquery,Scroll,Anchor,我动态生成一个html页面,我希望能够使用箭头键在其中上下导航,每次按下上下键时滚动到下一个锚点 这是我的代码(不起作用) 有什么想法吗?谢谢 使用变量存储锚列表,然后将键索引存储到当前锚列表,如下所示: $myAnchors = $('.js_anchor'); currentAnchor = -1; $(document).keydown(function(e){ if (e.keyCode == 40) { console.log('keydown');

我动态生成一个html页面,我希望能够使用箭头键在其中上下导航,每次按下上下键时滚动到下一个锚点

这是我的代码(不起作用)


有什么想法吗?谢谢

使用变量存储锚列表,然后将键索引存储到当前锚列表,如下所示:

$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');
        }
    }
});


请注意,它还没有经过测试,但如果还没有工作的话,应该已经接近工作状态。

我目前正在实施您的解决方案,我想我已经非常接近了。谢谢!欢迎光临。如果你被什么事情缠住了,请随时发表你的担忧,我会整天都在监视你。
$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');