Chrome 中的 Keydown 模拟正常触发但不是正确的键 [英] Keydown Simulation in Chrome fires normally but not the correct key

查看:24
本文介绍了Chrome 中的 Keydown 模拟正常触发但不是正确的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 html 页面中的给定 textarea 元素上模拟 keydown 事件.因为我使用的是 Chrome,所以我在我的变量上调用了 initKeyboardEvent 并传递了我想输入到 textarea 的 keyCode .这是我尝试过的:

I want to simulate keydown events on a given textarea element in an html page. Since I am using Chrome, I called initKeyboardEvent on my variable and I passed the keyCode I want to type into the textarea. Here is what I tried:

var keyEvent = document.createEvent('KeyboardEvent');
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
inputNode.dispatchEvent(keyEvent);

在此代码中,我正在输入字母 m,但是 textarea 仅获取 keyCode 13,即 Enter 键.所以,我尝试了一个我在网上看到的覆盖代码,该代码将值设置为 keyCodeVal,但没有成功.

In this code I'm typing the letter m however the textarea is only getting the keyCode 13 which is the Enter key. So, I tried an override code I saw online that sets the value to keyCodeVal, but with no success.

var keyEvent = document.createEvent('KeyboardEvent');
Object.defineProperty(keyEvent, 'keyCode', { 
                         get : function() {
                                 return this.keyCodeVal;
                         }
                        });
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
keyEvent.keyCodeVal = 77;
inputNode.dispatchEvent(keyEvent);

有人知道如何设置 keyCode 值吗?

Does anyone have an idea how to set the keyCode value?

推荐答案

非常非常接近...

您只需要覆盖 'which' 属性.下面是一些示例代码:

You just needed to override the 'which' property. Here's some sample code:

Podium = {};
Podium.keydown = function(k) {
    var oEvent = document.createEvent('KeyboardEvent');

    // Chromium Hack
    Object.defineProperty(oEvent, 'keyCode', {
                get : function() {
                    return this.keyCodeVal;
                }
    });     
    Object.defineProperty(oEvent, 'which', {
                get : function() {
                    return this.keyCodeVal;
                }
    });     

    if (oEvent.initKeyboardEvent) {
        oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k);
    } else {
        oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0);
    }

    oEvent.keyCodeVal = k;

    if (oEvent.keyCode !== k) {
        alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
    }

    document.dispatchEvent(oEvent);
}

示例用法:

Podium.keydown(65);

注意:此代码不适用于 IE、Safari 或其他浏览器.好吧,也许用 Firefox.天啊.

Note: this code is not designed to work in IE, Safari, or other browsers. Well, maybe with Firefox. YMMV.

这篇关于Chrome 中的 Keydown 模拟正常触发但不是正确的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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