简体   繁体   English

Greasemonkey Javascript 按键

[英]Greasemonkey Javascript Key Press

I'm currently trying to make a GreaseMonkey script that will allow a user to press left or right on their keyboard and have that go to a previous comic strip or go to the next strip.我目前正在尝试制作一个 GreaseMonkey 脚本,它允许用户在键盘上向左或向右按​​,然后转到上一个连环漫画或下一个连环漫画。 I currently have some code up but it's not giving me any results.我目前有一些代码,但它没有给我任何结果。

function KeyCheck()
{
var KeyID = event.keyCode;
alert(KeyID);
}

document.onKeyDown = KeyCheck();

The code is just for debugging to see if it's actually executing but when I press a key nothing will happen on the page.该代码仅用于调试以查看它是否实际执行,但是当我按下某个键时,页面上不会发生任何事情。 I'm testing in Firefox also.我也在 Firefox 中进行测试。

So after Googling for a good 30 minutes, I found out GreaseMonkey doesn't support onkeydown out of the box.所以在谷歌搜索了 30 分钟之后,我发现 GreaseMonkey 不支持开箱即用的 onkeydown。 I had to use a function called "addEventListener".我不得不使用一个名为“addEventListener”的函数。 My final code returns the keyCode of a key pressed on the site properly:我的最终代码正确返回网站上按下的键的 keyCode:

function KeyCheck(e)
{
alert(e.keyCode);
}

window.addEventListener('keydown', KeyCheck, true);

You shouldn't have the () after KeyCheck .您不应该在 KeyCheck 之后使用 () Your current code runs KeyCheck and then attempts to set document.onKeyDown to the value returned.您当前的代码运行 KeyCheck,然后尝试将 document.onKeyDown 设置为返回的值。 If you do it without the () it should instead set the function called KeyCheck to be run on the event.如果您在没有 () 的情况下执行此操作,则应将名为 KeyCheck 的函数设置为在事件上运行。

Also, I think onKeyDown should be all lower case - it's document.onkeydown .另外,我认为 onKeyDown 应该全部小写 - 它是document.onkeydown

Further example, with an inline function:进一步的例子,使用内联函数:

document.onkeydown = function() { alert("key down") }

works whereas工作而

document.onkeydown = alert("key down");

doesn't.没有。

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

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