如何在JavaScript中模拟按键? [英] How can I simulate a keypress in JavaScript?

查看:102
本文介绍了如何在JavaScript中模拟按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种模拟按键的方法。

I'm trying to find a way to simulate a keypress.

例如,当启动功能时,应按下向下箭头键,这样网页应略微滚动。

For example, when function launched, the key "Arrow Down" should be pressed and so the webpage should be slightly scrolled.

我只对Chrome感兴趣,jQuery或普通JS都适合。 (更优选的是普通JS。)

I'm interested only in Chrome, and both jQuery or plain JS will be appropriate. (Plain JS will be more preferable).

这是我尝试过的代码示例之一:

That's one of the code examples I tried:

var e = $.Event("keydown", { keyCode: 40}); // 40 = down arrow
$("body").trigger(e);
// When I launch it the console, nothing happens. The page is not scrolled.
// May be I missed some obvious?

我搜索并发现了以下相关问题,但解决方案对我不起作用:

I searched and found the following related questions, but the solutions did not work for me:

  • Definitive way to trigger keypress events with jQuery
  • Firing a Keyboard Event in JavaScript
  • How to trigger event in JavaScript?
  • Simulate left and right arrow key event with javascript
  • Simulate Keypress With jQuery
  • Simulating a Keypress Event from Javascript Console
  • Simulate JavaScript Key Events

换句话说

使用AutoHotkey,您可以轻松制作如下内容:

Using AutoHotkey, you can easily make something like:

Down::
Send, {Up}

然后,如果按向下箭头键,它将被触发向上。我只想用JS实现它。

Then, if you press Down arrow key, it will be triggered Up. I just want to implement it with JS.

推荐答案

正如@rfsbsb指出:用于模拟按键的查询脚本按下未运行的键盘快捷方式

As @rfsbsb pointed out from: Jquery script for simulated key press down not running keyboard shortcut


如果你试图触发一些浏览器或系统范围的键盘快捷键
那么它就是一个死胡同 - 它不能出于安全原因这样做。如果它可能是
,你可以在互联网上找到
的页面(例如)将它们自己添加到你的书签中,甚至不用询问
(通过使用Javascript触发CTRL + B快捷键) 。

If you're trying to fire some browser or system wide keyboard shortcut then it's a dead end - it can't be done for security reasons. If it would be possible, you would have pages all over the Internet that would (for example) add themself to your bookmarks without even asking (by firing CTRL+B shortcut using Javascript).

这篇关于如何在JavaScript中模拟按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆