Javascript JQuery在用户键入contenteditable时删除多个enter
当用户写东西时,有时他们会在一行中留下两个或更多的空格,有没有办法用jQuery来防止这种情况 例如: 我不允许用户这样键入:Javascript JQuery在用户键入contenteditable时删除多个enter,javascript,jquery,Javascript,Jquery,当用户写东西时,有时他们会在一行中留下两个或更多的空格,有没有办法用jQuery来防止这种情况 例如: 我不允许用户这样键入: Hi Dear, This is some text. Second text Thirt text and ..... Hi Dear, This is some text. Second text. Thirt text and.... var lastKey = ''; $("#id").keypress(function(e)
Hi Dear,
This is some text.
Second text
Thirt text and .....
Hi Dear,
This is some text.
Second text.
Thirt text and....
var lastKey = '';
$("#id").keypress(function(e){
if(e.which == 13 && lastKey == 13)
e.preventDefault()
lastKey = e.which;
});
所以我们需要删除多个空格行,如下所示:
Hi Dear,
This is some text.
Second text
Thirt text and .....
Hi Dear,
This is some text.
Second text.
Thirt text and....
var lastKey = '';
$("#id").keypress(function(e){
if(e.which == 13 && lastKey == 13)
e.preventDefault()
lastKey = e.which;
});
我想我们可以用jquerykeyup函数和regex一样来实现它
$(document).ready(function() {
$("body").on("keyup", ".text", function() {
var text = $(".text");
text = text.replace(/(\r\n|\r|\n){2}/g, '$1').replace(/(\r\n|\r|\n){3,}/g, '$1\n');
});
});
有办法吗?我可以用php正则表达式实现这一点。但是,当用户编写文本而不需要php时,有没有办法做到这一点
我想说的是,在写文本时不允许有额外的空格
<div class="text" contenteditable="true" placeholder="User can write text here More than three sub-spaces will not be allowed. "></div>
这样做:
Hi Dear,
This is some text.
Second text
Thirt text and .....
Hi Dear,
This is some text.
Second text.
Thirt text and....
var lastKey = '';
$("#id").keypress(function(e){
if(e.which == 13 && lastKey == 13)
e.preventDefault()
lastKey = e.which;
});
它检查连续两次按enter键,并忽略第二次。它比使用正则表达式更快、更干净。使用jquery
text
对textarea
不起作用,使用jqueryval
它总是起作用,并使用eventblur
它在用户离开textarea
时触发一次。如果您愿意,也可以使用change
这是工作代码
$('.text').on('blur' , function(){
$(this).val( $(this).val().replace(/\n\n+/g , "\n") )
})
您提供的代码段工作正常。删除多个enter后,您可能需要将文本插入回contenteditable<代码>$(“.text”).html(文本)。你面临的问题是什么?我已经更新了演示。这里是链接。