[英]Ctrl+Enter jQuery in TEXTAREA
How do I trigger something when the cursor is within TEXTAREA and Ctrl + Enter is pressed? 当光标在TEXTAREA中并按下Ctrl + Enter时,如何触发某些内容? Using jQuery . 使用jQuery 。 Thanks 谢谢
Actually this one does the trick and works in all browsers: 实际上这个技巧可以在所有浏览器中使用:
if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey)
link to js fiddle . 链接到js小提琴 。
Notes: 笔记:
keyCode
10, not 13 ( bug report ). 在Windows和Linux上的Chrome中, 输入将注册为keyCode
10,而不是13( 错误报告 )。 So we need to check for either. 所以我们需要检查一下。 ctrlKey
is control on Windows, Linux and macOS (not command ). ctrlKey
是Windows,Linux和macOS(不是命令 )的控件 。 See also metaKey
. 另见metaKey
。 You can use the event.ctrlKey
flag to see if the Ctrl key is pressed, something like this: 您可以使用event.ctrlKey
标志来查看是否按下了Ctrl键,如下所示:
$('#textareaId').keydown(function (e) {
if (e.ctrlKey && e.keyCode == 13) {
// Ctrl-Enter pressed
}
});
Universal solution 通用解决方案
Supports OS X as well, that is, both control + enter and command + enter should work. 也支持OS X,也就是说, control + enter和command + enter都应该有效。
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
// do something
}
I found answers of others either incomplete or not cross-browser compatible. 我发现其他人的答案不完整或不兼容跨浏览器。
This code works google chrome. 此代码适用于Google Chrome。
$(function ()
{
$(document).on("keydown", "#textareaId", function(e)
{
if ((e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey)
{
alert('ctrl+enter');
}
});
});
This can be extended to a simple-but-flexible JQuery plugin as in: 这可以扩展为一个简单但灵活的JQuery插件,如:
$.fn.enterKey = function (fnc, mod) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
fnc.call(this, ev);
}
})
})
}
Thus 从而
$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
should submit a form when the user presses ctrl-enter with focus on that form's textarea. 当用户按下ctrl-enter并重点放在该表单的textarea上时,应该提交一个表单。
(With thanks to https://stackoverflow.com/a/9964945/1017546 ) (感谢https://stackoverflow.com/a/9964945/1017546 )
first you have to set a flag when Ctrl is pressed, do this onkeydown. 首先你必须在按下Ctrl时设置一个标志,执行onkeydown。 then you have to check the keydown of enter. 然后你必须检查输入的keydown。 unset the flag when you see a keyup for Ctrl . 当您看到Ctrl的键盘时取消设置标志。
$('my_text_area').focus(function{ set_focus_flag });
//ctrl on key down set flag
//enter on key down = check focus flag, check ctrl flag
Maybe a little late to the game, but here is what I use. 也许游戏有点晚了,但这就是我用的东西。 It will also force submit of the form that is the current target of the cursor. 它还将强制提交作为光标当前目标的表单。
$(document.body).keypress(function (e) {
var $el = $(e.target);
if (e.ctrlKey && e.keyCode == 10) {
$el.parents('form').submit();
} else if (e.ctrlKey && e.keyCode == 13) {
$el.parents('form').submit();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.