简体   繁体   English

使用jQuery在38个字符后在文本区域中强制换行

[英]Forcing line break in the textarea after 38 characters using jquery

1 Heres is my code but I am dont know how to add a line break and allow the user to continue typing. 1这是我的代码,但我不知道如何添加换行符并允许用户继续输入。 With the alert message is fine but I just want the user to continue typing and line break added by the script. 带有警报消息很好,但我只希望用户继续键入脚本并添加换行符。

dom.query = jQuery.noConflict( true );
dom.query(document).ready(function() {
    // var myTA = dom.query('#remaining_chars');
    //alert(myTA[0].scrollHeight); 
    dom.query('#ta').keypress(function() {
        var text =dom.query(this).val();
        var arr = text.split("\n");
        for(var i = 0; i < arr.length; i++) {
            if(arr[i].length > 38) {
                alert("Not more than 38 characters per line! Continue in next line!");
                event.preventDefault(); // prevent characters from appearing
            }
        }

        console.log(text);
        dom.query('#ta').val(text);
    });
});

Link to the code : http://jsfiddle.net/e5w5z/8/ 1 链接到代码: http : //jsfiddle.net/e5w5z/8/ 1

This code will automatically insert line breaks if the user continues to type and never backtracks. 如果用户继续键入并且永不回溯,此代码将自动插入换行符。 This only analyzes the last line in the textarea. 这仅分析文本区域中的最后一行。 Therefore, if they go back to a previous line and begin editing, they will be able to type more than the max characters allowed per line. 因此,如果他们返回到上一行并开始编辑,他们将能够输入多于每行所允许的最大字符数。 It should be possible to have this analyze every line, but you'd have to write some more involved logic in order to insert line breaks at the correct positions and set the caret position properly after changing the textarea contents. 可以对每一行进行分析,但是您必须编写一些更复杂的逻辑,以便在更改textarea内容之后在正确的位置插入换行符并正确设置插入记号的位置。

JSFiddle: http://jsfiddle.net/7V3kY/1/ JSFiddle: http : //jsfiddle.net/7V3kY/1/

var LINE_LENGTH_CHARS = 38;

$(function(){

    $(document).on('input propertychange','textarea',function(e){
        // Something was typed into the textarea
        var lines = $(this).val().split("\n");
        var last_line = lines[lines.length-1];
            if (last_line.length >= LINE_LENGTH_CHARS) {

                // Resetting the textarea val() in this way has the 
                // effect of adding a line break at the end of the 
                // textarea and putting the caret position at the 
                // end of the textarea
                $(this).val($(this).val()+"\n");

            }
    });
});

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

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