1

我需要删除 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();
    }
}
4

1 回答 1

1
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");
        }
    }
}
于 2012-12-14T08:31:46.223 回答