简体   繁体   English

回应关键新闻javascript

[英]respond to key press javascript

I'm sorry if this is basic, but I've searched and found nothing that works. 如果这是基本的,我很抱歉,但我搜索过,发现没有任何效果。

I want to load a web page. 我想加载一个网页。 When that page loads, it displays an image. 加载该页面时,它会显示图像。 I want to have the page automatically start listening for a right arrow key press. 我想让页面自动开始监听右箭头按键。 When that happens, a function in my script will change the image (that part I have gotten to work by using a button that reacts when clicked). 当发生这种情况时,我的脚本中的一个函数将改变图像(我通过使用单击时响应的按钮来完成该部分)。

It's the listening for and reacting to a key press I cannot get to work. 这是我无法开始工作的关键新闻的倾听和反应。 Note that I'm using Safari, but I would like if possible for it to work in firefox or IE as well. 请注意,我正在使用Safari,但我想尽可能在​​Firefox或IE中使用它。

Please help thanks. 请帮助谢谢。

UPDATE TO RESPOND TO COMMENT: Here is what I tried, though I simplified the other part to make this shorter -- now it just writes a result to a div: 更新回应评论:这是我尝试过的,虽然我简化了另一部分以缩短它 - 现在它只是将结果写入div:

<html>
<head>
<script language="Javascript">
function reactKey(evt) {
   if(evt.keyCode==40) {
      document.getElementById('output').innerHTML='it worked';
   }
}
</script>
</head>
<body onLoad="document.onkeypress = reactKey();">
<div id="output"></div>
</body>
</html>

If you are using jquery, you can do this: 如果您使用的是jquery,则可以执行以下操作:

$(document).keydown(function(e){
    if (e.keyCode == 39) { 
       alert( "right arrow pressed" );
       return false;
    }
});

Easiest thing to do is use one of the many many many hotkey libraries, like https://github.com/jeresig/jquery.hotkeys or https://github.com/marquete/kibo . 最简单的方法是使用众多热键库中的一个,如https://github.com/jeresig/jquery.hotkeyshttps://github.com/marquete/kibo

EDIT: try something like this (after you've already loaded Kibo's javascript). 编辑:尝试这样的事情(在你已经加载了Kibo的javascript之后)。

In your body statement, add the onload handler: <body onload="setuphandler"> . 在body语句中,添加onload处理程序: <body onload="setuphandler">

Then add something like this (taken from the Kibo page): 然后添加这样的东西(取自Kibo页面):

<script type="text/javascript">
var k = new Kibo();
function setuphandler()
{
  k.down(['up', 'down'], function() {
  alert("Keypress");
  console.log('up or down arrow key pressed');
});
}
</script>
document.onkeydown= function(key){ reactKey(key); }

function reactKey(evt) {
   if(evt.keyCode== 40) {
      alert('worked');
   }
}

http://jsfiddle.net/dY9bT/1/ http://jsfiddle.net/dY9bT/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM