javascript 如何使用 jQuery 触发组合键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3893397/
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
How to trigger key combo with jQuery
提问by Fribu - Smart Solutions
I have coded some stuff:
我已经编码了一些东西:
http://fincha.com/kunden/schmitt/
http://fincha.com/kunden/schmitt/
I zoom in with .css("zoom")but I need the buttons to simulate CTRL+or CTRL-
我放大.css("zoom")但我需要按钮来模拟CTRL+或CTRL-
This code isn't working for me:
此代码对我不起作用:
e = jQuery.Event("keydown");
e.which = 50;
$("input").trigger(e);
Please help!
请帮忙!
EDIT
编辑
I actually wanted to zoom-inand zoom-outthe whole web page, not just a input field.
我实际上想要zoom-in和zoom-out整个网页,而不仅仅是一个输入字段。
回答by Matt Ball
jQuery normalizes modifier keys on events by setting one or more properties on the eventobject. So, you want to set event.ctrlKeyto true, so this should work for you:
jQuery 通过在event对象上设置一个或多个属性来规范化事件上的修饰键。所以,你想设置event.ctrlKey为true,所以这应该适合你:
e = jQuery.Event("keydown");
e.which = 50;
e.ctrlKey = true;
$("input").trigger(e);
However, as per a comment at source (linked below):
但是,根据来源的评论(链接如下):
You cannot easily change values in the event object (probably for security reasons).
您无法轻松更改事件对象中的值(可能是出于安全原因)。
So, if you're unable to set the event's properties after constructing the Eventobject, then you can $.extend()it to set the ctrlKeyproperty:
因此,如果您在构造Event对象后无法设置事件的属性,那么您可以$.extend()设置该ctrlKey属性:
e = jQuery.Event("keydown");
fake = $.extend({}, e, {which: 50, ctrlKey: true});
$("input").trigger(fake);
One other thing: I'm not sure if you're trying to use key code 50for the +or the -keys. Maybe you are, and you're using a different keyboard layout, but according to this demo, 50is the JavaScript key code for hitting 2- so that could also be part of your problem.
另一件事:我不确定您是否尝试将密钥代码50用于+或-密钥。也许您是,并且您正在使用不同的键盘布局,但根据此演示,50是用于点击的 JavaScript 键代码2- 因此这也可能是您的问题的一部分。
Source: comments on a jQuery API page.
Edit:
编辑:
All this aside, I don't think you can actuallychange the browser's zoom level using JavaScript, even if you're "sending" the keyboard command to do so.
撇开所有这些不谈,我认为您实际上无法使用 JavaScript 更改浏览器的缩放级别,即使您“发送”了键盘命令来这样做。
回答by Stephen
Source: http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
来源:http: //www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
});
This is for Ctrl+s, but you should be able to modify it easily.
这是用于 Ctrl+s,但您应该能够轻松修改它。

