Javascript 将 CR/LF 插入文本区域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5682088/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:26:16 来源:igfitidea点击:
Insert a CR/LF into a textarea
提问by Phillip Senn
I've got the following code:
我有以下代码:
document.onkeydown=function(e) {
if (e.which == 13 && isCtrl) {
log('Ctrl CR');
} else if (e.which == 17) {
isCtrl = true;
};
I need to insert a Carriage Return/Line feed where the cursor is located in the input textarea. Now that I think about it, I should probably be using a textarea selector instead of document.onkeydown, but $('textarea').onkeydown doesn't work.
我需要在光标位于输入文本区域的位置插入回车/换行。现在我考虑一下,我可能应该使用 textarea 选择器而不是 document.onkeydown,但是 $('textarea').onkeydown 不起作用。
回答by Matt Ball
$('textarea').keydown(function (e){
var $this = $(this);
if (e.which === 13 && e.ctrlKey) {
$this.val($this.val() + '\r\n'); // untested code (to add CRLF)
}
});