17

我想把我的问题说清楚。请不要将其与确定按键混淆。我不希望用户按任何键。相反,我想运行一个触发 Escape 按键事件的脚本。请帮忙!

4

2 回答 2

37

您可以使用$.Event()创建一个包含 keydown 事件的 Event 对象,其中 keyCode 为 27(应该是 Esc),例如:

var esc = $.Event("keydown", { keyCode: 27 });
$("body").trigger(esc); // change body to the element where you'd like to execute the escape key press.

在 jquery.com 上查看这个工作演示和文档

另请注意,正如 Christofer 所说,这可能不适用于所有浏览器和环境,因为它可能被认为是可能以恶意方式使用的可疑行为- 就像不会发生带有外部 href的点击事件一样. 我在 Chrome、Safari、Opera、FF 和 IE9 中成功地测试了这个(Esc)。<a>

于 2012-04-09T08:18:49.863 回答
8

For security reasons, some browsers (not sure if all), prevent you from firing keydown-events. Please refer to this article for more info.

A quote from the article:

Safari/Chrome makes the keyCode and charCode properties read-only, so it is not possible to simulate specific keys when manually firing events.

于 2012-04-09T08:02:00.013 回答