簡體   English   中英

限制文本區域中單行的行數和字母數

[英]Limiting number of lines & letters in single line in textarea

我正在嘗試將文本區域中的行數限制為20,對於IE8瀏覽器,每行中的字符數限制為15。 我嘗試了像https://stackoverflow.com/a/11586266/1453499這樣的stackoverflow上已經可用的解決方案,但是它們都可以在chrome和IE8中無法使用的其他現代瀏覽器中使用。 是否有與IE8兼容的解決方案?

我使用兩個答案的組合( https://stackoverflow.com/a/3373056/1453499https://stackoverflow.com/a/11586266/1453499 )找到解決問題的方法,以下是最終解決方案

    function getInputSelection(el) {
        var start = 0, normalizedValue, range,
            textInputRange, len, endRange;

        if (typeof el.selectionStart === "number" && typeof el.selectionEnd === "number") {
            start = el.selectionStart;
        } else {
            range = document.selection.createRange();

            if (range && range.parentElement() === el) {
                normalizedValue = el.value.replace(/\r\n/g, "\n");
                len = normalizedValue.length;

                // Create a working TextRange that lives only in the input
                textInputRange = el.createTextRange();
                textInputRange.moveToBookmark(range.getBookmark());

                // Check if the start and end of the selection are at the very end
                // of the input, since moveStart/moveEnd doesn't return what we want
                // in those cases
                endRange = el.createTextRange();
                endRange.collapse(false);

                if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                    start = len;
                } else {
                    start = -textInputRange.moveStart("character", -len);
                    start += normalizedValue.slice(0, start).split("\n").length - 1;
                }
            }
        }

        return start;
    }

    $(document).ready(function() {
        //Restrict the search 
        var textArea = $('#textarea_id');
        var maxRows = 30;
        var maxChars = 17;
        textArea.keypress(function(e) {
            var text = textArea.val();
            var lines = text.split('\n');
            if (e.keyCode === 13) {
                return lines.length < maxRows;
            } else { //Should check for backspace/del/etc.
                var caret = getInputSelection(textArea.get(0));
                var line = 0;
                var charCount = 0;
                $.each(lines, function(i, e) {
                    charCount += e.length;
                    if (caret <= charCount) {
                        line = i;
                        return false;
                    }
                    //\n count for 1 char;
                    charCount += 1;
                });

                var theLine = lines[line];
                return theLine.length < maxChars;
            }
        });

    });

暫無
暫無

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

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