簡體   English   中英

在第5行之后刪除textarea中的字符

[英]delete characters in textarea after 5th line

我需要在textarea中第5行之后的每個字符都將被刪除的功能,並且第5行最多只能包含15個字符。

我可以使用“插入符”來實現這一點,但是它只會在特定的光標位置添加文本,即時消息使用kepress事件和setinterval(textarea的onFocus)函數,該函數將從textarea中清除多余的文本,而clearInterval(textarea的onBlur)

function insertTextAtCaret(el, text) 
{
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}
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");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM