我发现了这种方式,但有了它,我只能在.which
中设置一个键码,我想模拟键 ALT + space + x 同时。
ALT 我可以使用.altKey = true;
$(".btn").click(function() {
var e = jQuery.Event("keypress");
e.which = 88; // x code value
e.altKey = true; // Alt key pressed
$("input").trigger(e);
});
如何添加空格键码?
答案 0 :(得分:0)
我为之前的回答道歉。我想过如何处理。现在我修改代码来处理和触发:
您可以使用两个事件来实现它:keyDown和keyUp,如下所示:
var x,
alt,
space;
document.addEventListener('keydown', function (e) {
e = window.event ? event : e;
switch (e.keyCode) {
case 88:
x = true;
break;
case 18:
alt = true;
break;
case 32:
space = true;
break;
}
});
document.addEventListener('keyup', function (e) {
if (x && alt && space) {
alert("alt + space + x Pressed!");
}
x = alt = space = false;
});
function triggerEvent(eventName, keyCode) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.keyCode = keyCode || null;
if (document.createEvent) {
document.dispatchEvent(event);
} else {
document.fireEvent('on' + event.eventType, event);
}
}
triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');