How to fire keyboard events in Javascript?

╄→尐↘猪︶ㄣ 提交于 2019-12-04 05:37:31

问题


I'm giving a value to a textbox and then giving focus to it.

document.getElementById('textbox').value="abcd";
document.getElementById('textbox').focus();

Then, I am creating a keyboard event and trying to fire the CTRL+A key combination (trying to select the text inside the textbox) by writing the following code:

var myEvent = document.createEvent('KeyboardEvent');

myEvent.initKeyEvent("keypress", true, true, window, true, false, false, false, 0, 97);

document.getElementById('textbox').dispatchEvent(myEvent);

But the above code doesn't select the text inside the textbox.

How to select the text creating the keyboard event ?


回答1:


You can't trigger browser keypress behavior with JavaScript simulated keypresses. You can only trigger your own function. What that means if that if you add a keypress event listener that checks if the a key is pressed and then does something, you can trigger that behavior, but you can't for example make the browser pull up it's "find" bar when you trigger ctrl+F. That would be a security issue.

The appropriate way would be to write your own function for selecting and fire it whenever you need it.

This should do what you're looking for: Live demo (click).

<input type="text" id="my-input" value="Some text.">

JavaScript:

var myInput = document.getElementById('my-input');

myInput.addEventListener('click', function() {
  this.focus();
  this.select();
});

var event = new Event('click');
myInput.dispatchEvent(event);


来源:https://stackoverflow.com/questions/21354060/how-to-fire-keyboard-events-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!