Animated scrolling from anchor to anchor using the

2019-07-25 03:44发布

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.

Here's my code (doesn't work)

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

Any ideas ? Thanks !

1条回答
Lonely孤独者°
2楼-- · 2019-07-25 04:38

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; 
    }
}

And replace

$(window).animate({scrollTop: $myAnchors.eq(currentAnchor).offset().top}, 2000,'easeInOutCubic');

by

$(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.

查看更多
登录 后发表回答