最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Navigate to rel=next and rel=prev page using left and right arrow - Stack Overflow

programmeradmin1浏览0评论

I have a page with prev and next links:

<link rel="prev" href=";#63;referer=index.php"> 
<link rel="next" href=";#63;referer=index.php"> 

Is it possible to use Javascript to navigate these links if the user presses Left arrow or Right arrow? The link should not activate if they are editing text and the Left or Right arrow is pressed.

This will be used to simplify viewing several image pages.

I have a page with prev and next links:

<link rel="prev" href="http://camera.phor/cameralife/photos/11096&#63;referer=index.php"> 
<link rel="next" href="http://camera.phor/cameralife/photos/5679&#63;referer=index.php"> 

Is it possible to use Javascript to navigate these links if the user presses Left arrow or Right arrow? The link should not activate if they are editing text and the Left or Right arrow is pressed.

This will be used to simplify viewing several image pages.

Share Improve this question asked Sep 4, 2011 at 19:59 William EntrikenWilliam Entriken 39.5k23 gold badges158 silver badges211 bronze badges 1
  • A word of accessibility caution: this can hijack arrow keys as screen readers use them to navigate through page elements: webaim/techniques/keyboard – Dave Everitt Commented May 10, 2023 at 20:25
Add a ment  | 

2 Answers 2

Reset to default 4

Without jQuery: http://jsfiddle/UXPLt/1/.

document.onkeyup = function(e) { // key pressed
    if(document.activeElement.nodeName === "INPUT"
    || document.activeElement.nodeName === "TEXTAREA") {
        return; // abort if focusing input box
    }

    var elems = document.getElementsByTagName("link"),
        links = {};

    for(var i = 0; i < elems.length; i++) { // filter link elements
        var elem = elems[i];
        if(elem.rel === "prev") { // add prev to links object
            links.prev = elem;
        } else if(elem.rel === "next") { // ad next to links object
            links.next = elem;
        }
    }

    if(e.keyCode === 37) { // left key
        location.href = links.prev.href;
    } else if(e.keyCode === 39) { // right key
        location.href = links.next.href;
    }
};
$(document).keydown(function(e){
        if (e.keyCode == 37) {  // left
           $( "a[rel='prev']" ).click();
           return false;
        } else if (e.keyCode == 39) {  // right
           $( "a[rel='next']" ).click();
           return false;
        }
    });
发布评论

评论列表(0)

  1. 暂无评论