3 回答
TA贡献1883条经验 获得超3个赞
一个非jquery版本,适用于webkit和gecko:
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
40, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
TA贡献1784条经验 获得超7个赞
如果你可以使用jQuery 1.3.1:
function simulateKeyPress(character) { jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });}$(function() { $('body').keypress(function(e) { alert(e.which); }); simulateKeyPress("e");});
添加回答
举报