[英]Trigger keypress event with event listener WITHOUT jquery
我想在不使用 jQuery 的情況下觸發按鍵事件作為對事件偵聽器的反應
let arrow = document.querySelector("#arrow"); //When you click on the arrow arrow.addEventListener('click', function(e){ // It triggers a keypress (down) $(document).trigger(keypressing); });
[編輯] 我試過了,但似乎沒有觸發模擬按鍵:
let arrow = document.querySelector(".scroll-down"); arrow.addEventListener('click', function(e){ console.log('simulating the keypress of down arrow') document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'})); }); $(window).bind('keypress', function(event) { if (event.key == 'x') { console.log('its working with x') } });
您可以使用dispatchEvent
來觸發事件。
示例:使用鍵x
觸發keypress
document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));
這對我觸發按鍵事件很有用:
// Create listener
document.addEventListener('keydown', () => { console.log('test')})
// Create event
const keyboardEvent = document.createEvent('KeyboardEvent');
const initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
keyboardEvent[initMethod](
'keydown', // event type: keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // view: should be window
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
40, // keyCode: unsigned long - the virtual key code, else 0
0 // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
// Fire event
document.dispatchEvent(keyboardEvent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.