通过 jquery 调用 Escape 按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10070464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invoke Escape key press event by jquery
提问by Lakshay
I want to make my question clear. Please dont confuse it with determining the key press. I dont want the user to press any key. On the contrary, I want to run a script which fires the Escape key press event. Please help!
我想把我的问题说清楚。请不要将它与确定按键混淆。我不希望用户按任何键。相反,我想运行一个触发 Escape 按键事件的脚本。请帮忙!
回答by m90
You can use $.Event()
to create an Event object containing a keydown event with the keyCode of 27 (which should be Esc) like:
您可以使用$.Event()
keyCode 为 27(应该是 Esc)来创建一个包含 keydown 事件的 Event 对象,例如:
var esc = $.Event("keydown", { keyCode: 27 });
$("body").trigger(esc); // change body to the element where you'd like to execute the escape key press.
See this working demoand the docs at jquery.com
请参阅此工作演示和jquery.com 上的文档
Also note that, as stated by Christofer, this might not be working in all browsers and environments as it might be considered shadybehavior that couldbe used in a malicious manner - just like triggering a click event on an <a>
with an external href will not happen. I successfully tested this (the Esc) in Chrome, Safari, Opera, FF & IE9 though.
另请注意,正如 Christofer 所述,这可能不适用于所有浏览器和环境,因为它可能被视为可以以恶意方式使用的可疑行为- 就像在具有外部 href 的情况下触发点击事件一样不会发生. 不过,我在 Chrome、Safari、Opera、FF 和 IE9 中成功地测试了这个(Esc)。<a>
回答by Christofer Eliasson
For security reasons, some browsers (not sure if all), prevent you from firing keydown-events. Please refer to this articlefor 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.
Safari/Chrome 将 keyCode 和 charCode 属性设为只读,因此无法在手动触发事件时模拟特定键。