使用 jQuery 触发按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16122380/
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
Trigger Keypress with jQuery
提问by Tommy Nicholas
On the Definitive Trigger Keypress jQuery threadthere is no working JSFiddle for the answer, and the code that is there doesn't work for me.
在Definitive Trigger Keypress jQuery 线程上,没有可用的 JSFiddle 答案,并且那里的代码对我不起作用。
$("button").click(function () {
$("input").focus();
var e = jQuery.Event("keydown");
e.which = 77; // # Some key code value
$("input").trigger(e);
})
There's my code and here's my fiddle http://jsfiddle.net/Z8adb/
这是我的代码,这是我的小提琴 http://jsfiddle.net/Z8adb/
On click, an M should appear in the input, as the input is given focus and having a keydown with the keyCode of 77 ("m") triggered on it.
单击时,输入中应出现 M,因为输入已获得焦点并触发 keyCode 为 77(“m”)的按键按下。
Any ideas?
有任何想法吗?
EDIT: My true purpose for this is to trigger an "m" hotkey on a Sublime Video in order to mute the video programmatically. This was my first step to ensure I was firing the "m" key properly, which I am with the help of Stack Overflow. However, I'm still not able to get an event to fire programmatically on the video. I think this is just a problem with Sublime Video, but I'm not sure, and anyone's views on forcing keypresses and clicks would be awesome to hear.
编辑:我这样做的真正目的是在 Sublime Video 上触发“m”热键,以便以编程方式使视频静音。这是我确保正确触发“m”键的第一步,这是我在 Stack Overflow 的帮助下完成的。但是,我仍然无法在视频上以编程方式触发事件。我认为这只是 Sublime Video 的一个问题,但我不确定,任何人对强制按键和点击的看法都会很棒。
回答by PSL
Using trigger you are just triggering the event with a keycode but not assigning the value to the textbox. Try this :- http://jsfiddle.net/PbHD2/
使用触发器,您只是使用键码触发事件,而不是将值分配给文本框。试试这个:- http://jsfiddle.net/PbHD2/
$("button").click(function() {
$("input").focus();
var e = jQuery.Event("keydown");
e.which = 77; // # Some key code value
$("input").val(String.fromCharCode(e.which));
$("input").trigger(e);
});
$('input').keydown(function(e){
console.log('Yes keydown triggered. ' + e.which)
});
回答by Moby's Stunt Double
SublimeVideo is a HTML5 player, correct. If so, you can mute it by using a property, right?
SublimeVideo 是一个 HTML5 播放器,没错。如果是这样,您可以使用属性将其静音,对吗?
$("video#yourVideoTagId").prop("muted", true);