简体   繁体   English

模拟使用keypress的dispatchEvent按下的键盘键

[英]Simulate a keyboard key pressed with dispatchevent of keypress

Can someone help me with this code. 有人可以帮我这个代码。 I am trying to simulate a keyboard input for a web page without specifically specifying the control to send it to. 我正在尝试模拟网页的键盘输入,而没有特别指定发送它的控件。 I am trying to do so through createEvent and dispatchEvent. 我正在尝试通过createEvent和dispatchEvent这样做。 but when I receive the actual keypressed the event does not have any reference to the character. 但是当我收到实际的按键时,该事件没有对该字符的任何引用。 The charCode, keyCode and which are always 0. charCode,keyCode和始终为0。

Thanks for your help! 谢谢你的帮助! Max 最高

<html>
<body> 
    <button type="button" onclick="KeyPressInject('e')">TEST</button>
</body>

<script type="text/javascript">

addEventListener("keypress", function(event){ EventKeyPressed(event)}); 

function KeyPressInject(letter)
{
    var evt = document.createEvent("KeyboardEvent");
    Object.defineProperty(evt, 'keyCode', { 
                         get : function() {
                                 return this.keyCodeVal;
                         } });      
    evt.initKeyboardEvent ("keypress", true, false, window, false, false, false, false, letter, letter); 
    var canc = !window.dispatchEvent(evt);
}

function EventKeyPressed(event)
{
    console.log("Key Pressed " + event.charCode);
}   
</script>
</html>

Please see if this helps, I've prepared a simple fiddle: Basically it triggers a keypress event 请查看是否有帮助,我准备了一个简单的小提琴: 基本上,它会触发按键事件

You give it the character and the element to fire: 您给它赋予角色和触发元素:

simulateKeyPress("e", 'body');

It's different from your code that it needs to define the character pressed through the which property. 它与您的代码不同,它需要定义通过which属性按下的字符。

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

相关问题 模拟被按下的键盘上的按钮,将该键的值添加到文本输入中 - Simulate a button on the keyboard being pressed, add the value of that keypress to text input 当在CKEditor小部件内按下另一个键时模拟标签键按下 - Simulate tab keypress when another key is pressed inside CKEditor widget jQuery 事件按键:按下了哪个键? - jQuery Event Keypress: Which key was pressed? 使用jQuery触发按键...并指定按下了哪个键 - Trigger a keypress with jQuery…and specify which key was pressed 按下键获取输入值并按下捕获键 - Get value of input with keypress and capture key pressed 模拟 G Sheet 上按下 Enter 键 Java - Simulate enter key pressed on G Sheet Java AngularJS-对按键事件做出反应,并用其他按键替换按键 - AngularJS - react to a keypress event and replace pressed key with other key 可以模拟通过使用JavaScript单击链接来按下键盘快捷方式吗? - Possible to simulate a keyboard shortcut being pressed by clicking on link using JavaScript? jQuery datepicker 在不按下 CTRL 键的情况下更改按键上的日期 - jQuery datepicker change date on keypress without CTRL key pressed 按下 Enter 键时如何触发 Tab 按键? - How can I fire the Tab keypress when the Enter key is pressed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM