将CR / LF插入文本区域

时间:2011-04-15 20:34:19

标签: javascript jquery

我有以下代码:

document.onkeydown=function(e) {
if (e.which == 13 && isCtrl) {
   log('Ctrl CR');
} else if (e.which == 17) {
   isCtrl = true;
};

我需要在光标位于输入文本区域中的位置插入回车符/换行符。 现在我考虑一下,我应该使用textarea选择器而不是document.onkeydown,但$('textarea')。onkeydown不起作用。

1 个答案:

答案 0 :(得分:7)

$('textarea').keydown(function (e){
    var $this = $(this);
    if (e.which === 13 && e.ctrlKey) {
        $this.val($this.val() + '\r\n'); // untested code (to add CRLF)
    }
});

参考