简体   繁体   English

在文本区域中的10个字符后放置换行符

[英]Put line break after 10 characters in text area

I have a text area that can take 10000 characters. 我有一个可以容纳10000个字符的文本区域。 i want to put the line breaker on each line of the text area value after 10 character 我想将换行符放在10个字符后的文本区域值的每一行

something like this i want to achive 这样的事情我想实现

11111111 1
111 111 11
11 11 11 1

all above line has 10 characters each. 以上所有行各有10个字符。

var start = 3
var times = 1;
$('.mydesc').keyup(function () {
    var len = $(this).val().length;
    if (len == start) {
        this.value += '\n';
        times = ++times;
        start= ((start * 2) + start);
    }
});

but doesn't work .. 但不起作用..

Simplest solution is to always re-add all of the new-lines: 最简单的解决方案是始终重新添加所有换行符:

$('.mydesc').keyup(function () {
    this.value = this.value
                     .replace(/[\n\r]+/g, "")
                     .replace(/(.{10})/g, "$1\n");
});

http://jsfiddle.net/s4cUz/ http://jsfiddle.net/s4cUz/

Something like this would do it: 这样的事情可以做到:

http://jsfiddle.net/Zxuj7/ http://jsfiddle.net/Zxuj7/

$('#test_textarea').keyup(function () {
   var new_stuff = $(this).val();
       new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
   var test = new_stuff.replace(/(.{10})/g,"$1\n");
   $(this).val(test);
});

However, be aware that it doesn't work that well with the "deleting" of characters. 但是,请注意,“删除”字符并不能很好地工作。 If you give it a go, you will notice that when you actually delete a character and the code runs, it will put you at the end of the textarea again (because its "overwriting" the value) 如果放手一搏,您会注意到,当您实际删除一个字符并运行代码时,它将再次使您进入文本区域的末尾(因为它“覆盖”了该值)

UPDATE: 更新:

You may actually be better formatting AFTER they have finished editing the textarea - ie using blur() ; 实际上,在他们完成了textarea的编辑之后,您可能会更好地格式化-即使用blur()

$('#test_textarea').blur(function () {
    // leaving the field... so lets try and format nicely now
    var new_stuff = $(this).val();
           new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
           new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
    $(this).val(new_stuff);
});

Although that doesn't do it in real time - it does work better when deleting/editing the contents 尽管这不能实时进行-在删除/编辑内容时效果更好

Enhanced version of Andrew Newby's script: Andrew Newby脚本的增强版:

$('#test_textarea').keyup(function (e) {
     if (e.keyCode === 8) return; // Backspace
     var new_stuff = $(this).val();
     new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
     new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
     $(this).val(new_stuff);
});

This actually ignores backspace key, so at least that interaction is preserved. 这实际上忽略了退格键,因此至少保留了交互。

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

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