有没有办法在Javascript中只发送shift键(不与其他键组合)?
我知道我可以使用evt.shiftKey
检测 Shift键,但我如何 发送 只有换班钥匙?
我试过了:
$.event.trigger({type:'keypress', which : character.charCodeAt(16) });
我的console.log给了我:Uncaught ReferenceError: character is not defined
答案 0 :(得分:1)
使用KeyboardEvent
作为构造函数,您可以在 vanilla JavaScript 中执行以下操作
var e = new KeyboardEvent('keypress', {shiftKey: true});
node.dispatchEvent(e);
其中node
是目标元素
更完整
function press_shift(target, /*optional*/ bubbles, /*optional*/ events) {
var o = {shiftKey: true};
if (bubbles) o.bubbles = true;
if (!events && events !== 0) events = -1;
if ((events & 1) === 1) target.dispatchEvent(new KeyboardEvent('keydown', o));
if ((events & 2) === 2) target.dispatchEvent(new KeyboardEvent('keypress', o));
if ((events & 4) === 4) target.dispatchEvent(new KeyboardEvent('keyup', o));
}
press_shift.keydown = 1;
press_shift.keypress = 2;
press_shift.keyup = 4;
// and then for example, to just do a keypress which bubbles up the DOM
press_shift(document.body, true, press_shift.keypress);
答案 1 :(得分:0)
您可以使用“keydown”事件。它会给你你想要的结果。
document.addEventListener('keydown', function(evt){
console.log(evt);
});