使用带有jQuery的键盘从锚到锚的动画滚动 [英] Animated scrolling from anchor to anchor using the keyboard with jQuery

查看:55
本文介绍了使用带有jQuery的键盘从锚到锚的动画滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态生成一个html页面,我希望能够使用箭头键上下浏览,每次按UP或DOWN时滚动到下一个锚点.

I generate dynamically a html page and I'd like to be able to navigate through it up and down with the arrow keys, scrolling to the next anchor each time I press UP or DOWN.

这是我的代码(无效)

$(document).keydown(function(e){
    if (e.keyCode == 40) {
        console.log('keydown');
        if ( next === undefined ) {
            next = $('.js_anchor').next();
        } else {
            next = next.next();
        } 
        $(document).animate({scrollTop: next}, 2000,'easeInOutCubic');
    }
});

有什么想法吗?谢谢!

推荐答案

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

Use a variable to store the anchor list and then the key index to the current one like so:

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

如果用户自己滚动并按下向下箭头,则可能会向上滚动,这会产生一些不良影响.使用此功能来确定要滚动到的内容:

This have some bad effects if the user scrolls by himself and presses the down arrow it might scroll up... Use this function to determine which to scroll to:

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

请注意,它尚未经过测试,但如果尚未运行,应该接近工作状态.

Please take note that it has NOT been tested but should be close to working, if not already working.

这篇关于使用带有jQuery的键盘从锚到锚的动画滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆