Javascript 如何检测“shift+enter”并在Textarea中生成新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6014702/
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
How do I detect "shift+enter" and generate a new line in Textarea?
提问by TIMEX
Currently, if the person presses enterinside the text area, the form will submit.
Good, I want that.
目前,如果人enter在文本区域内按下,则表单将提交。
很好,我想要那个。
But when they type shift+ enter, I want the textarea to move to the next line: \n
但是当他们输入shift+ 时enter,我希望 textarea 移动到下一行:\n
How can I do that in JQuery
or plain JavaScript as simple as possible?
我怎样才能在JQuery
JavaScript中或纯 JavaScript 中尽可能简单地做到这一点?
采纳答案by Jishnu A P
Better use simpler solution:
更好地使用更简单的解决方案:
Tim's solution below is better I suggest using that: https://stackoverflow.com/a/6015906/4031815
下面蒂姆的解决方案更好,我建议使用它:https: //stackoverflow.com/a/6015906/4031815
My solution
我的解决方案
I think you can do something like this..
我认为你可以做这样的事情..
EDIT :Changed the code to work irrespective of the caret postion
编辑:无论插入符号的位置如何,都将代码更改为工作
First part of the code is to get the caret position.
代码的第一部分是获取插入符号位置。
Ref: How to get the caret column (not pixels) position in a textarea, in characters, from the start?
参考:如何从一开始就以字符为单位在 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;
}
And then replacing the textarea value accordingly when Shift+ Entertogether , submit the form if Enteris pressed alone.
然后在Shift+ Entertogether时相应地替换 textarea 值,如果Enter单独按下则提交表单。
$('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();
}
}
});
Here is a demo
这是一个演示
回答by Tim Down
Easy & Elegant solution:
简单优雅的解决方案:
First, pressing Enterinside a textarea does not submit the form unless you have script to make it do that. That's the behaviour the user expects and I'd recommend against changing it. However, if you must do this, the easiest approach would be to find the script that is making Entersubmit the form and change it. The code will have something like
首先,Enter在 textarea 内按下不会提交表单,除非您有脚本来执行此操作。这是用户期望的行为,我建议不要更改它。但是,如果您必须这样做,最简单的方法是找到Enter提交表单的脚本并对其进行更改。代码会有类似的东西
if (evt.keyCode == 13) {
form.submit();
}
... and you could just change it to
...你可以把它改成
if (evt.keyCode == 13 && !evt.shiftKey) {
form.submit();
}
On the other hand, if you don't have access to this code for some reason, you need to do the following to make it work in all major browsers even if the caret is not at the end of the text:
另一方面,如果由于某种原因您无法访问此代码,则即使插入符号不在文本末尾,您也需要执行以下操作以使其在所有主要浏览器中都能正常工作:
jsFiddle: http://jsfiddle.net/zd3gA/1/
jsFiddle:http: //jsfiddle.net/zd3gA/1/
Code:
代码:
function pasteIntoInput(el, text) {
el.focus();
if (typeof el.selectionStart == "number"
&& typeof el.selectionEnd == "number") {
var val = el.value;
var selStart = el.selectionStart;
el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
el.selectionEnd = el.selectionStart = selStart + text.length;
} else if (typeof document.selection != "undefined") {
var textRange = document.selection.createRange();
textRange.text = text;
textRange.collapse(false);
textRange.select();
}
}
function handleEnter(evt) {
if (evt.keyCode == 13 && evt.shiftKey) {
if (evt.type == "keypress") {
pasteIntoInput(this, "\n");
}
evt.preventDefault();
}
}
// Handle both keydown and keypress for Opera, which only allows default
// key action to be suppressed in keypress
$("#your_textarea_id").keydown(handleEnter).keypress(handleEnter);
回答by Matt Goodwin
Most of these answers overcomplicate this. Why not try it this way?
这些答案中的大多数都使问题变得过于复杂。为什么不试试这种方式呢?
$("textarea").keypress(function(event) {
if (event.keyCode == 13 && !event.shiftKey) {
submitForm(); //Submit your form here
return false;
}
});
No messing around with caret position or shoving line breaks into JS. Basically, the function will not run if the shift key is being pressed, therefore allowing the enter/return key to perform its normal function.
没有乱七八糟的插入符号位置或推线中断到 JS。基本上,如果按下 shift 键,该功能将不会运行,因此允许输入/返回键执行其正常功能。
回答by Liam Hall
Why not just
为什么不只是
$(".commentArea").keypress(function(e) {
var textVal = $(this).val();
if(e.which == 13 && e.shiftKey) {
}
else if (e.which == 13) {
e.preventDefault(); //Stops enter from creating a new line
this.form.submit(); //or ajax submit
}
});
回答by Thariama
Use the jQuery hotkeysplugin and this code
使用jQuery 热键插件和此代码
jQuery(document).bind('keydown', 'shift+enter',
function (evt){
$('textarea').val($('#textarea').val() + "\n");// use the right id here
return true;
}
);
回答by Tombery
回答by Shrroy
Using ReactJS ES6 here's the simplest way
在这里使用 ReactJS ES6 是最简单的方法
shift+ enterNew Line at any position
shift+enter在任何位置换行
enterBlocked
enter被封锁
class App extends React.Component {
constructor(){
super();
this.state = {
message: 'Enter is blocked'
}
}
onKeyPress = (e) => {
if (e.keyCode === 13 && e.shiftKey) {
e.preventDefault();
let start = e.target.selectionStart,
end = e.target.selectionEnd;
this.setState(prevState => ({ message:
prevState.message.substring(0, start)
+ '\n' +
prevState.message.substring(end)
}),()=>{
this.input.selectionStart = this.input.selectionEnd = start + 1;
})
}else if (e.keyCode === 13) { // block enter
e.preventDefault();
}
};
render(){
return(
<div>
New line with shift enter at any position<br />
<textarea
value={this.state.message}
ref={(input)=> this.input = input}
onChange={(e)=>this.setState({ message: e.target.value })}
onKeyDown={this.onKeyPress}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
回答by Spencer Sullivan
I found this thread looking for a way to control Shift + any key. I pasted together other solutions to make this combined function to accomplish what I needed. I hope it helps someone else.
我发现这个线程正在寻找一种控制 Shift + 任意键的方法。我将其他解决方案粘贴在一起,使这个组合功能完成我需要的功能。我希望它可以帮助别人。
function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
// Shift + anything is not desired
if (e.shiftKey) {
return false;
}
// allow backspace, tab, delete, enter, arrows, numbers
//and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
回答by Hsinhsin Hung
I use div by adding contenteditable true instead of using textarea.
我通过添加 contenteditable true 而不是使用 textarea 来使用 div。
Hope can help you.
希望能帮到你。
$("#your_textarea").on('keydown', function(e){//textarea keydown events
if(e.key == "Enter")
{
if(e.shiftKey)//jump new line
{
// do nothing
}
else // do sth,like send message or else
{
e.preventDefault();//cancell the deafult events
}
}
})
回答by M?h?mm?d ?am?m
This works for me!
这对我有用!
$("#your_textarea").on('keydown', function(e){
if(e.keyCode === 13 && !e.shiftKey)
{
$('form').submit();
}
});