2012-12-07 90 views
2

我正在做一个画廊,并试图找出如何编程箭头键导航画廊。下一个点击键按

因此,按下左箭头会去到以前的图片网址:

function window.location = 'http://www.example.com/prevphoto.php'; 

按右箭头会去到下一个图像的URL。

function window.location = 'http://www.example.com/nextphoto.php'; 

更新(感谢Haxxed指着我在正确的方向) 这是我在哪里,但它不工作。你能明白为什么吗?

$('body').keypress(function (e) { 
    if (e.which == 37) { 
     // Left Arrow Pushed 
     window.location = "/prevphoto.php"; 
    } else if (e.which == 39) { 
     // Right Arrow Pushed 
     window.location = "/nextphoto.php"; 
    } 
}); 
+0

向我们展示一些代码或发布jsFiddle。 – glortho

+0

谢谢大家的意见。他们都帮助。 –

回答

2

基本上你需要使身体标记有一个按键事件(或使用jQuery做一个事件侦听器),然后只检查键码(左箭头是37,右为39),然后使用window.location重定向页面。 All Key Codes

<head> 
    <script> 
      function e(event){ 
      if(event.keyCode == 37){ 
       //Left Arrow Pushed 
       window.location = "../prevphoto.php"; 
      }else if(event.keyCode == 39){ 
       //Right Arrow Pushed  
       window.location = "../nextphoto.php"; 
      }   
     } 
    </script> 
</head>  
<body onKeyPress="e(event)" > 

</body>​ 
1

尝试把脚本在你的脑袋标签,然后修改body使用document

$(document).keypress(function (e) { 

    if (e.which == 37) { 
     //Left Arrow Pushed 
     window.location = "/prevphoto.php"; 
    } else if (e.which == 39){ 
     //Right Arrow Pushed  
     window.location = "/nextphoto.php"; 
    } 

}); 
+0

是的,这似乎是合乎逻辑的,但它也不起作用。这里的网站[链接](http://www.zacharysheldon.com/print/17/Sunset-Light-at-Night) –

+0

嗯,它适用于我。用箭头键没问题... –