开发者

Add arrow key navigation to jQuery scrollTop

开发者 https://www.devze.com 2023-02-20 08:22 出处:网络
I\'m using jQuery scrollTop to navigate through points on a page. Works great. But I was wondering if it would be possible to add up/down arrow key navigation to it. So for instance, down arrow scroll

I'm using jQuery scrollTop to navigate through points on a page. Works great. But I was wondering if it would be possible to add up/down arrow key navigation to it. So for instance, down arrow scrolls to the next point, next point, etc. Up arrow goes back one point, etc, etc. Any help on this one is greatly appreciated!

HTML:

<a class="bookmark" href="#option1">Option 1</a>
<a class="bookmark" href="#option2">Option 2</a>
<a class="bookmark" href="#opti开发者_如何学Con3">Option 3</a>

<div id="option1">Stuff</div>
<div id="option2">Stuff</div>
<div id="option3">Stuff</div>

jQuery

$( '.bookmark' ).click(function() {
    var elementClicked = $(this).attr( "href" );
    var destination = $(elementClicked).offset().top;
        $("html:not(:animated),body:not(:animated)")
           .delay( 300 ).animate({ scrollTop: destination-20}, 700 );
    return false;
});


Something like this should be what you're looking for.

Could easily add something that determines what section of the page you're on before moving incase the user scrolls with the mouse!

var navPoints = [
            '#option1',
            '#option2',
            '#option3',
            '#option4',
            '#option5'
        ];

        var currentPoint = 0;

        var moveToElement = function() {
            var elementTop = $(navPoints[currentPoint]).offset().top;
            $("html:not(:animated),body:not(:animated)").delay( 300 ).animate({ scrollTop: elementTop-20}, 700 );
        }

        $(document).keyup(function(e) {
            switch (e.which) {
                case 38:
                    // Up Arrow
                    if(currentPoint > 0)
                        currentPoint--;
                    break;
                case 40:
                    // Down Arrow
                    if(currentPoint < navPoints.length - 1)
                        currentPoint++;
                    break;
                default:
                    // Some other key
                    return;
            }

            moveToElement();
        });


Not exactly an answer to your question, but jscrollpane has this feature built in, if you wanted to try using that.

In the initialization you just enter { showArrows: true; } and done.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号