0

我有一个 textarea 字段,当用户按下回车键时提交信息。以下是我所拥有的:

$(document)ready(function(){
    $('textarea').on('keypress',function(e){
        var txt;
        txt = $(this).val();

        if(e.which == 13)
        {
            //submit the form
        }

    });
});

我想做的是在用户按回车键时提交信息,并在用户按住控制键并按回车键时进行硬返回。(上面的代码工作正常)我只是不知道如何为按住选项添加其他代码。请解释答案。

4

2 回答 2

2

您可以使用e.ctrlKey

$(document).ready(function(){
    $('textarea').on('keypress',function(e) {
        var txt=$(this).val();

        if(e.which === 13 || e.which === 10) {
            if (e.ctrlKey) {
                // handle ctrl-ret here
            } else {
                //submit the form
            }
        }
  });
});

相关问题:在 javascript/jQuery 中检测 ctrl+tab 按键

于 2013-04-26T01:47:57.537 回答
1

下面是一个完全符合您要求的解决方案。JSfiddle 中的代码有一些 CSS 来向您展示它的工作原理。当您按 Enter 时,它将更改文本区域的颜色(您将用您的代码替换它以进行提交)但是当您按 Shift+Enter 时,它将创建一个新行并继续编辑。

干杯:D

http://jsfiddle.net/5Kc2T/1/

$(document).ready(function () {
    $('textarea').on('keypress', function (e) {
        var txt = $(this);

        if (e.which == 13) {
            e.preventDefault();
            if (e.shiftKey === true) {
                txt.val(txt.val() + "\n");
            } else {
                //Submit Code Here
            }
        }
    });
});
于 2013-04-26T02:18:50.533 回答