如何检测“shift + enter”并在Textarea中生成一个新行? [英] How do I detect "shift+enter" and generate a new line in Textarea?

查看:95
本文介绍了如何检测“shift + enter”并在Textarea中生成一个新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,如果用户在文本区域中按输入,表单将提交。

好​​,我想要。

Currently, if the person presses enter inside the text area, the form will submit.
Good, I want that.

但是当他们键入 shift + 输入时,我想textarea移动到下一行: \\\

But when they type shift + enter, I want the textarea to move to the next line: \n

如何在 JQuery 中尽可能简单? >

How can I do that in JQuery or plain JavaScript as simple as possible?

推荐答案

我认为你可以这样做..

I think you can do something like this..

EDIT:已将代码更改为工作,而不考虑插入位置

EDIT : Changed the code to work irrespective of the caret postion

代码的第一部分是获取插入位置。

First part of the code is to get the caret position.

参考文献: textarea中的插入位置,字符开始

function getCaret(el) { 
    if (el.selectionStart) { 
        return el.selectionStart; 
    } else if (document.selection) { 
        el.focus();
        var r = document.selection.createRange(); 
        if (r == null) { 
            return 0;
        }
        var re = el.createTextRange(), rc = re.duplicate();
        re.moveToBookmark(r.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
    }  
    return 0; 
}

然后在 Shift + 一起输入,如果单独按下 Enter 则提交表单。

And then replacing the textarea value accordingly when Shift + Enter together , submit the form if Enter is pressed alone.

$('textarea').keyup(function (event) {
    if (event.keyCode == 13) {
        var content = this.value;  
        var caret = getCaret(this);          
        if(event.shiftKey){
            this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length);
            event.stopPropagation();
        } else {
            this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
            $('form').submit();
        }
    }
});

这里是 demo

这篇关于如何检测“shift + enter”并在Textarea中生成一个新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆