简体   繁体   中英

keyboard shortcuts with navigation menu

could some one please integrate my code with keyboard keys to navigate up and down with less code as possible (my site is heavy enough!). i've tried some plugins and searched alot but my little experience does not help me!

$(function() {
$('ul.nav a').each(function(i, elem) {
    $(elem).bind('click', function(event) {
        event.preventDefault();
        var offset = i * 38;
        $('ul.nav').stop().animate({backgroundPosition: '0 ' + offset + 'px'}, 2000,'easeOutQuart');

        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 2000,'easeOutQuart');
            $('ul.nav a').css({'cursor': 'pointer', 'color': '#643D21'});
            $anchor.css({'cursor': 'default', 'color': '#995D32'});
        event.preventDefault();
    });
});
});

HTML code

    <ul class="nav">
    <li><a href="#what">what</a></li>
    <li><a href="#who">who</a></li>
    <li><a href="#portfolio">portfolio</a></li>
    <li><a href="#contact">contact</a></li>
</ul>

appreciated,

if you just want a press on '1' to be mapped to '#what', I'd do something like this:

$("document").keypress(function(event) {
  if ( event.which == XX ) {
     location.href="#what";
   }

An alternative is to give your links an id="" and use

$('#<ID OF ELEMENT>').click();

instead of

location.href="#what";

Here XX is the keypress-value for your key. For '1' it's 50. You can use this site to figure out wich key has what value in the example at the bottom. put the cursor in the input-field and press a key. Look for "which" in the output.

Also be aware that this applies to a keypress anywhere on the page. If your want to restrict it to when the mouse is oevr a certain element, modify $('document') to whichever element the keypress-event should be active in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM