简体   繁体   English

使用javascript或jquery对textarea进行自动换行

[英]wordwrap for textarea using javascript or jquery

I need functionality that textarea should contain max 5 lines and each line should contain max 15 chars, when user writes 2 words eg 123456 123456789 and if that line char limit exceeds 15, then it should bring the 2nd word in next line along with \\n char in first line (means 123456 will be in first line along with \\n and 123456789 will be in 2nd) , I need to maintain \\n (replacing <br >) in my db for some reasons. 我需要的功能是textarea最多包含5行,每行最多包含15个字符,当用户写2个单词(例如123456 123456789)时,如果该行的字符数限制超过15,则应该将第二个单词与\\n一起带到下一行焦炭在第一行(指123456将在第一线沿\\n and 123456789将在2日),我需要保持\\n (更换<br在我的数据库因某些原因)。

i wrote this code, which gives fuzzy result in some conditions 我写了这段代码,在某些情况下给出了模糊的结果

<textarea onkeypress="charCountTextarea('txt1',event,'75','14')" id="txt1"></textarea> 

var countLines=0;

var newLines;

function charCountTextarea(textAreaId,e,limit,lineLen)
{   

       newLines = $("#"+textAreaId).val().split("\n").length;
       var t = $("#"+textAreaId)[0];
       var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;

    //console.log("new lines"+lineIndex);
        if(newLines >= 5 && $("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)
        {

            if( e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
            {
                e.preventDefault();
                return false;
            }
        }


        else
        if($("#"+textAreaId).val().split("\n")[lineIndex].length>=lineLen)  // which will count the total line char condition
        {
            console.log($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1]);


            if($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1].indexOf(" ")==-1 && e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex != 4 && newLines<5)
            {
                // to bring the word in next line
                var str = $("#"+textAreaId).val(), replacement = '\n';
                str = str.replace(/ ([^ ]*)$/,replacement+'$1');
                $("#"+textAreaId).val(str);

            }
            else
            if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex!=4 && newLines<5)
            {
                // to insert next line              
                insertTextAtCaret(document.getElementById(textAreaId), "\n");
            }


        }

        if(e.keyCode == 13 && newLines >= 5) 
        {
            //linesUsed.css('color', 'red');
            e.preventDefault();
            return false;
        }

}
function charCountTextarea(textAreaId,e,limit,lineLen)
{   

    var code = e.charCode || e.keyCode;

    newLines = $("#"+textAreaId).val().split("\n").length;
    var t = $("#"+textAreaId)[0];
    var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
    console.log('val t :'+$("#"+textAreaId).val()+' line index : '+lineIndex+' new lines '+newLines);

    if(lineIndex == 10 && $("#"+textAreaId).val().split("\n")[lineIndex].length>(lineLen+1) && code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
    {
        $("#"+textAreaId).val(($("#"+textAreaId).val()).substring(0, $("#"+textAreaId).val().length - 1));
        alert('You are reached to limit');
        return false;
    }

    if(lineIndex<5)
    {
        $("#"+textAreaId).val($("#"+textAreaId).val().wordWrap(lineLen, "\n", 0));
    }
    var countLine1 = $("#"+textAreaId).val().split("\n")[0].length;

    if($("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)  // which will count the total line char condition
    {
        console.log("In condition : ");
        if(code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
        {
            // to insert next line              
            insertTextAtCaret(document.getElementById(textAreaId), "\n");
        }
    }
}

You can not know if the input will be fed using keyboard. 您不知道输入是否将使用键盘输入。 I could just use the mouse to paste a text there. 我可以只用鼠标在此处粘贴文本。

I would rely on a function that would constantly check the input and take the action you want, which I would execute using the setInterval() function once the textarea is focused, which then gets cleared using clearInterval() once the textarea loses focus. 我将依靠一个会不断检查输入并执行所需操作的函数,一旦文本区域被聚焦,我将使用setInterval()函数执行该功能,一旦文本区域失去焦点,则将使用clearInterval()将其清除。

And this function would use a RegExp to process the input and split it into necessary lines. 并且此函数将使用RegExp来处理输入并将其分成必要的行。

EDIT: Here's what I mean. 编辑:这就是我的意思。

$('body').on('focus','#txt1',function(e) {
    $(this).data('int',setInterval(checkInput,1));
}).on('blur','#txt1',function(e) {
    clearInterval($(this).data('int'));
    $(this).removeData('int');
});

function checkInput() {
    var val = $('#txt1').val();
    // process val here
    $('#txt1').val(val);
}

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

相关问题 如何使用Javascript / Jquery模拟在文本区域中的键入? - How to simulate typing into a textarea using Javascript/Jquery? javascript / jquery中的编码器textarea - coder textarea in javascript/jquery IE6的Textarea问题-我正在将Jquery框架用于javascript - Textarea issue with IE6 - I'm using Jquery framework for javascript 使用javascript / jquery在文本区域内用强标签包装突出显示的文本 - Wrap highlighted text within textarea with strong tags using javascript/jquery 在提交之前使用JavaScript / jQuery将TextArea的内容转换为纯文本 - Using JavaScript/jQuery to convert content of TextArea to plain text before submitting 如何使用Javascript(而非jQuery)提取文本区域中的每个字符 - How to extract each character in a textarea using Javascript (not jQuery) 如何使用JavaScript或jQuery将一些文本插入textarea? - How can I insert some text into a textarea using JavaScript or jQuery? 如何通过使用javascript / jQuery重新选择textarea中的选定文本? - How to re-select the selected text in textarea by using javascript/jQuery? 使用JavaScript / jQuery在textarea中渲染乘法和除法符号 - render multiplication and division signs in textarea using JavaScript / jQuery 渲染文本区域时使用Javascript / jQuery触发事件 - Using Javascript/jQuery to trigger event when textarea rendered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM