1

以下 jQuery-less 代码有效:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

keyboardEvent[initMethod](
               "keydown", // event type : keydown, keyup, keypress
                true, // bubbles
                true, // cancelable
                window, // viewArg: should be window
                false, // ctrlKeyArg
                false, // altKeyArg
                false, // shiftKeyArg
                false, // metaKeyArg
                17, // keyCodeArg : unsigned long the virtual key code, else 0
                0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
element.dispatchEvent(keyboardEvent);

...并且应该在许多浏览器中工作,而不是这个更简单的解决方案:
jQuery keydown trigger not working

我试图找到一种方法让 jQuery 做同样的事情,但不幸的是,下面的代码不起作用:

var evt = $.Event('keydown');
evt.which = 17;
evt.keyCode = 17; // Ctrl
$(element).trigger(evt);


如果您想测试您的解决方案,这里是完整的 GreaseMonkey 脚本:http:
//userscripts.org/scripts/review/486617

4

0 回答 0