[英]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.