【问题标题】:Trigger keypress event with event listener WITHOUT jquery使用没有 jquery 的事件侦听器触发按键事件
【发布时间】:2020-10-07 09:28:31
【问题描述】:

我想在不使用 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')
}
});

【问题讨论】:

  • 使用.click()
  • 你的#arrow 元素是什么?输入 ?按钮?
  • 是一个div容器,包裹了3个span

标签: javascript dom-events keypress


【解决方案1】:

您可以使用dispatchEvent 来触发事件。
示例:使用键 x 触发 keypress

document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));

docs


这对我触发按键事件很有用:

// 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);

【讨论】:

  • arrow.addEventListener('click', function(e) { console.log('模拟向下箭头的按键') document.dispatchEvent(new KeyboardEvent('keypress', {'keyCode': '40'})); });为了按向下箭头键?
  • 它没有触发模拟按键
  • 好吧,诺伯特,它就像一个魅力。但是我很失望,因为当您单击按钮时,我基本上想向下滚动(与向下箭头键相同)。所以现在它在控制台中显示了测试,所以可以肯定键盘事件被触发了,但是 console.log 没有任何事情发生
猜你喜欢
  • 1970-01-01
  • 2020-09-06
  • 2015-12-18
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 2010-12-27
相关资源
最近更新 更多