不允许在文本区域中换行
使用 jQuery 如何不允许插入新行(通过按 Enter 或复制文本)- 在半伪代码中...
$('textarea').keydown(function(){
$(this).remove_new_lines();
});
谢谢!
编辑:
它会像下面一样粗糙还是有更好的方法?
function removeNL(s){
return s.replace(/[\n\r\t]/g,);
}
$('textarea').keydown(function(){
$(this).val(removeNL($(this).val));
});
Using jQuery how can I not allow new lines to be inserted (by pressing enter or copying in text) - In semi-pseudo code...
$('textarea').keydown(function(){
$(this).remove_new_lines();
});
Thanks!
EDIT:
Would it be as crude as the following or is there a better way?
function removeNL(s){
return s.replace(/[\n\r\t]/g,);
}
$('textarea').keydown(function(){
$(this).val(removeNL($(this).val));
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两种方法可以做到这一点:在输入时检查每个字符,如果您不希望它显示,则返回 false,或者在每次更改/键入时您可以检查整个内容。虽然前者的性能更高,但在用户粘贴包含不需要的字符的内容的情况下它不起作用。因此,我推荐后一种方法,如下所示(这将禁止所有垂直空白):
使用 jQuery:
或使用纯 JavaScript (ES2015/ES6):
另一种方法是等到焦点离开文本区域,然后应用转变。这可以避免使用合成的、有条件的活动键盘控件的操作系统上的卡顿行为。不过,用户在离开该字段之前都会看到换行符,因此请注意。为此,只需将上述事件侦听器更改为侦听
blur
而不是keyup
。如果您使用 React,那么您已经制作了它,因为它可以避免移动浏览器的问题,同时让您可以使用受控组件在值更改时对其进行管理:
There are two methods to do this: check each character as it is input and return false if you don't want it to show up, or on each change/keyup you can check the entire contents. While the former is more performant, it won't work in situations where the user pastes content in that includes unwanted characters. For that reason, I recommend the latter approach, something like this (which will disallow all vertical whitespace):
With jQuery:
Or using plain JavaScript (ES2015/ES6):
Another approach is to wait until the focus leaves the textarea, then apply the transformation. This avoids janky behavior on operating systems using synthetic, conditionally active keyboard controls. The user will see newlines until they leave the field, though, so be aware. To do this, just change the above event listener to listen for
blur
rather thankeyup
.If you're using React, you have it made because it avoids issues with mobile browsers while letting you manage the value as it changes using controlled components:
你可以检查 keyCode,如果它等于 13,则返回 false
you can check keyCode, if it is equal to 13 simply return false