开发者

Navigate to section of page with 'j' and 'k' keys

开发者 https://www.devze.com 2023-04-02 08:32 出处:网络
I\'m trying to find the simplest code, whether it\'s standalone or with jQuery, that does this: when I press j on my keyboard, I\'m redirected to the next div below and when开发者_如何学运维 I press k

I'm trying to find the simplest code, whether it's standalone or with jQuery, that does this: when I press j on my keyboard, I'm redirected to the next div below and when开发者_如何学运维 I press k, I'm sent back to the div above. Extra points if it can scroll smoothly.


I think you'll want to use a combination of the following two plugins:

http://plugins.jquery.com/project/hotkeys

and

http://plugins.jquery.com/project/ScrollTo

which you could use in this kind of fashion:

$(document).bind('keydown', 'j', whenyoupressj);
$(document).bind('keydown', 'j', whenyoupressk);

and the actually scrolling part could be:

$.scrollTo( '#someid', 800, {easing:'elasout'} );


I would do this with jQuery in a way like this:

$(document).keydown(function (e) {

    // Handle only [J] and [K]...
    if (e.keyCode < 74 || e.keyCode > 75) {
        return false;
    }

    // Find the "active" container.
    var active = $('div.active').removeClass('active');
    var newActive;

    // Handle [J] event.
    if (e.keyCode == 74) {
        newActive = active.next('div');

        //if (newActive.index() == -1) {
        //    newActive = $('div', container).last();
        //}
    }
    // Handle [K] event.
    else if (e.keyCode == 75) {
        newActive = active.prev('div');

        //if (newActive.index() == -1) {
        //    newActive = $('div', container).first();
        //}
    }

    if (newActive !== undefined) {
        newActive.addClass('active');
        $(document).scrollTop(newActive.position().top);
    }
});
0

精彩评论

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