繁体   English   中英

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

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

1这是我的代码,但我不知道如何添加换行符并允许用户继续输入。 带有警报消息很好,但我只希望用户继续键入脚本并添加换行符。

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);
    });
});

链接到代码: http : //jsfiddle.net/e5w5z/8/ 1

如果用户继续键入并且永不回溯,此代码将自动插入换行符。 这仅分析文本区域中的最后一行。 因此,如果他们返回到上一行并开始编辑,他们将能够输入多于每行所允许的最大字符数。 可以对每一行进行分析,但是您必须编写一些更复杂的逻辑,以便在更改textarea内容之后在正确的位置插入换行符并正确设置插入记号的位置。

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