Keyboard Navigation to load pages

孤街醉人 提交于 2019-12-11 06:38:09

问题


is there a quick way to use the right and left arrow keys to load the next page? My solution so far is:

$(document).ready(function () {
    $("a.transition").click(function (event) {
        event.preventDefault();
        linkLocation = this.href;
        $("body").fadeOut(20, redirectPage);

    });
    $("a.transitionB").click(function (event) {
        event.preventDefault();
        linkLocation = this.href;
        $("body").fadeOut(20, redirectPage);

    });
    function redirectPage() {
        window.location = linkLocation;
    }
});

with 2 invisible link layers. But i need something to control the transition without clicking in the page, but to use the arrow buttons.

Thank you for your help.


回答1:


Try this (different browser == different keycodes):

function redirectPage(href) {
    window.location = href;
}

function onKey(e) {
    var key = e.keyCode ? e.keyCode : e.which;

    if (key == 37 || key == 26) {
        e.preventDefault();
        $("a.transition").click();
    } else if (key == 39 || key == 27) {
        e.preventDefault();
        $("a.transitionB").click();
    }
}

$(document).ready(function () {
    $(document).keypress(onKey);
    $("a.transition, a.transitionB").click(function (event) {
        event.preventDefault();
        $("body").fadeOut(20, function() {redirectPage(this.href)});
    });
});



回答2:


$(document).keyup(function(e) {
    console.log(e.keyCode);
});

Edit :

$(document).keyup(function(e) {
  switch(e.keyCode) {
    case 37 : alert('You pressed Left'); break;
    case 38 : alert('You pressed Up'); break;
    case 39 : alert('You pressed Right'); break;
    case 40 : alert('You pressed Down'); break;
   }
});

You can give it a try here http://jsbin.com/uzigu4



来源:https://stackoverflow.com/questions/3768738/keyboard-navigation-to-load-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!