我正在尝试找到一种模拟按键的方法。
例如,当功能启动时,应按下“向下箭头”键,因此网页应稍微滚动。
我只对 Chrome 感兴趣,jQuery 或纯 JS 都合适。 (纯 JS 会更可取)。
这是我尝试过的代码示例之一:
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?
我搜索并找到了以下相关问题,但解决方案对我不起作用:
- 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,您可以轻松制作如下内容:
Down::
Send, {Up}
然后,如果您按Down
方向键,会触发Up
。我只是想用JS来实现它。
最佳答案
正如@rfsbsb指出的那样:Jquery script for simulated key press down not running keyboard shortcut
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 - 如何在 JavaScript 中模拟按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143695/