如何在Javascript中触发键盘事件? [英] How to fire keyboard events in Javascript?

查看:114
本文介绍了如何在Javascript中触发键盘事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给文本框一个值,然后把焦点放在它上面。

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

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

然后,我正在创建一个键盘事件并尝试触发 CTRL 通过编写以下代码+ A 组合键(尝试在文本框中选择文本):

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.

如何选择创建键盘事件的文本?

推荐答案

您无法使用JavaScript模拟按键触发浏览器按键行为。您只能触发自己的功能。这意味着如果你添加一个按键事件监听器来检查 a 键是否被按下然后做某事,你可以触发这种行为,但你不能让浏览器拉起来触发 ctrl + F 时,它是查找栏。这将是一个安全问题。

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:

JavaScript:

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

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

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

这篇关于如何在Javascript中触发键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆