在没有jquery的情况下,用事件监听器触发按键事件。

问题描述 投票:1回答:1

我想在不使用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')
}
});
javascript dom-events keypress
1个回答
2
投票

你可以使用 dispatchEvent 来触发事件。例如:触发 keypress 带钥匙 x

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);
© www.soinside.com 2019 - 2024. All rights reserved.