how to get the arrow keys on the keyboard to trigger navigation (previous/next page) links within a blog

后端 未结 2 1339
醉梦人生
醉梦人生 2021-02-01 23:42

the script i\'ve pieced together so far looks like this:



        
相关标签:
2条回答
  • 2021-02-02 00:29

    Use this to tell you the keyIdentifier attribute of the object.

    <html>
    <head>
    
    <script type="text/javascript">
      document.onkeydown = function() {
      alert (event.keyIdentifier);
    }; 
    </script>
    </head>
    <body>
    </body>
    </html>
    

    Then you can use if-then logic to ignore all key presses you aren't interested in, and wire the correct behavior to the ones you are.

    The following will assign the left and right arrow keys to your links (based on the id of the anchor/link elements).

    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function() {
                document.onkeydown = function() 
                    {
                        var j = event.keyIdentifier
                        if (j == "Right")
                            window.location = nextUrl
                        else if (j == "Left")
                            window.location = prevUrl            
                            }
                       });
    
          $(document).ready(function() {
                        var nextPage = $("#next_page_link")
                        var prevPage = $("#previous_page_link")
                        nextUrl = nextPage.attr("href")
                        prevUrl = prevPage.attr("href")
                    });
    
    </script>
    </head>
    <body>
    <p>
        <a id="previous_page_link" href="http://www.google.com">Google</a> 
        <a id="next_page_link" href="http://www.yahoo.com">Yahoo</a>
    </p>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-02-02 00:47
    function leftArrowPressed() {
       // Your stuff here
    }
    
    function rightArrowPressed() {
       // Your stuff here
    }
    
    document.onkeydown = function(evt) {
        evt = evt || window.event;
        switch (evt.keyCode) {
            case 37:
                leftArrowPressed();
                break;
            case 39:
                rightArrowPressed();
                break;
        }
    };
    
    0 讨论(0)
提交回复
热议问题