How to change page with Javascript for keyboard na

2019-08-29 23:10发布

问题:

I would like to allow keyboard navigation for a photo gallery website (one page, one photo). What's the Javascript function to do this? I use the code below to manage keyboard events, and I would like to know how to implement goToPage() function.

Thanks.

document.onkeydown = checkKeycode;
function checkKeycode(e) {
  var keycode;
  if (window.event)
    keycode = window.event.keyCode;
  else
    if (e) keycode = e.which;
  switch (keycode) {
    case 37:  // left arrow
      goToPage("page1.htm");
      break;
    case 39:  // right arrow
      goToPage("page3.htm");
      break;
  }
}

回答1:

You need a document.location:

function checkKeycode(e)
{
  var keycode;

  if (window.event)
    keycode = window.event.keyCode;
  else
    if (e) keycode = e.which;

  switch (keycode)
  {
    case 37:  // left arrow
      document.location = "page1.htm";
    break;

    case 39:  // right arrow
      document.location = "page3.htm";
    break;
  }
}


回答2:

As long as your pages are neatly named, you could use

document.location = "http://www.myURL"

But you'll need a cycle for your pages. There are many ways of doing this, such as appending a number to a string that you pass:

var count = 0;
var html;
function previous(){
   html = "http://www.page" + count + ".htm"
   document.location = html;
}
function next(){
   var count +=1;
   html = "http://www.page" + count + ".htm"
   document.location = html;
}

or storing the strings in an array etc.