简体   繁体   English

如何添加 \\n 进入按键

[英]How add \n to enter key press

I need add '\\n' to my text area tag when user press Enter key.当用户按下 Enter 键时,我需要将 '\\n' 添加到我的文本区域标签中。 Because default enter add only visual new string, if i copy text from text area in other place i have one string.因为默认输入只添加视觉新字符串,如果我从其他地方的文本区域复制文本,我有一个字符串。
If i try如果我尝试

 $('.body__textarea').on('keydown', function (e) {
   if ( e.keyCode === 13 ) {
     e.preventDefault();
     const oldValue = $(this).val();
     const newValue = oldValue + '\n'
     $(this).val(newValue);
   }  
 })

New line adds in the end of string, but need where is caret.新行添加在字符串的末尾,但需要插入符号的位置。

Code example https://codepen.io/kostikovmu/pen/oNXqmoM代码示例https://codepen.io/kostikovmu/pen/oNXqmoM

You should use <br>你应该使用<br>
instead of \\n而不是\\n

Solution for me was change "copy" event:我的解决方案是更改“复制”事件:

const source = document.querySelector('.body__textarea');

source.addEventListener('copy', (event) => {
  const selection = document.getSelection();
  event.clipboardData.setData('text/plain', selection.toString());
  event.preventDefault();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM