给定一个textarea,是否有一种方法来限制基于#行的长度? [英] Given a textarea, is there a way to restrict length based on # of lines?

查看:86
本文介绍了给定一个textarea,是否有一种方法来限制基于#行的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea字段,我想让用户能够输入不超过3行。



这是否可能?

解决方案

a href =http://jsfiddle.net/nvLBZ/1/ =nofollow> http://jsfiddle.net/nvLBZ/1/



我刚刚(2小时)创建了一个脚本,总是将文本区域的高度限制为3行。


  1. 字符的最大可能宽度是针对特定文本区域计算的(如果尚未计算得更早)。


  2. textarea被克隆,以测试是否需要继续该函数。


  3. 否则,克隆的textarea用作引用,用户的textarea被删除。


  4. 使用有效的方法填充textarea:已知小于textarea宽度的块被添加到

  5. 当添加的块超过最大大小时,将逐个删除最后一个字符,直到最大行限制最终到达为止。

  6. 默认值已恢复。

代码位于底部( $(document))。 ready(...))。

 (function(){
var wordWidthMappers = {};
function checkHeight(textarea,maxLines){
if(!(textarea instanceof $))return; / * JQuery是必需的* /
if(isNaN(maxLines)|| !isFinite(maxLines)|| maxLines == 0)return;
var areaWidth = textarea.width();
var oldHeight = textarea.css(height);
var oldOverflow = textarea.css(overflow-y);
var lineHeight = parseFloat(textarea.css(line-height));
var maxTxtHeight = maxLines * lineHeight +px;

/ *计算有效率的确定* /
var fontstyles =font-size:+ textarea.css(font-size);
fontstyles + =; font-family:+ textarea.css(font-family);
fontstyles + =; font-weight:+ textarea.css(font-weight);
fontstyles + =; font-style:+ textarea.css(font-style);
fontstyles + =; font-variant:+ textarea.css(font-variant);
var wordWidth = wordWidthMappers [fontstyles];
if(!wordWidth){
var span = document.createElement(span);
span.style.cssText = fontstyles +; display:inline; width:auto; min-width:0; padding:0; margin:0; border:none;
span.innerHTML =W; // Widest character
document.body.appendChild(span);
wordWidth = wordWidthMappers [fontstyles] = $(span).width();
document.body.removeChild(span);
}

textarea = textarea [0];
var temparea = textarea.cloneNode(false);
temparea.style.visibility =hidden;
temparea.style.height = maxTxtHeight;
temparea.value = textarea.value;
document.body.appendChild(temparea);
/*Math.round是必要的,以处理浏览器特定的解释
的高度* /
if(Math.round(temparea.scrollHeight / lineHeight)> maxLines){
textarea.value =;
textarea.style.visibility =hidden;
if(oldOverflow!=scroll)textarea.style.overflowY =hidden;
textarea.style.height = maxTxtHeight;
var i = 0;
var textlen = temparea.value.length;
var chars_per_line = Math.floor(areaWidth / wordWidth);
while(i <= textlen){
var curLines = Math.round(textarea.scrollHeight / lineHeight);
if(curLines< = maxLines){
var str_to_add = temparea.value.substring(i,i + chars_per_line);
var nextLn = str_to_add.indexOf(\\\
);
if(nextLn> 0)str_to_add = str_to_add.substring(0,nextLn);
else if(nextLn == 0)str_to_add =\\\
;
i + = str_to_add.length;
textarea.value + = str_to_add;
} else if(curLines> maxLines){
textarea.value = textarea.value.substring(0,textarea.value.length-1);
i--;
if(Math.round(textarea.scrollHeight / lineHeight)< = maxLines)break;
}
}
textarea.style.visibility =visible;
textarea.style.height = oldHeight;
textarea.style.overflowY = oldOverflow;
}
temparea.parentNode.removeChild(temparea);
}

$(document).ready(function(){/ *添加检查器到文档* /
var tovalidate = $(#myTextarea);
tovalidate.keyup(function(){
/ *添加keyup事件处理程序可选:onchange * /
checkHeight(tovalidate,3);
});
} ;
})();


I have a textarea field and I want the user to be able to enter not more than 3 lines.

Is that possible?

解决方案

Fiddle: http://jsfiddle.net/nvLBZ/1/

I have just (2 hours) created a script which always restricts the height of the text-area to 3 lines.

  1. The largest possible width of a character is calculated for the specific textarea (if not already calculated earlier).
  2. The minimum words per line are calculated.
  3. The textarea is cloned, to test whether it's necessary to continue with the function. When the input is valid, the function returns without interrupting the user.

  4. Otherwise, the cloned textarea is used as a reference, and the user's textarea is erased. The user's textarea is also temporary invisible, for performance reasons.

  5. The textarea gets filled using an efficient method: Blocks which are known to be smaller than the textarea's width are added into the textarea.
  6. When the added blocks exceed the maximum size, the last characters are individually removed, until the maximum line limit has finally reached.
  7. The defaults are restored.

Code below, the code is implemented at the bottom ($(document).ready(...)).

(function(){        
    var wordWidthMappers = {};
    function checkHeight(textarea, maxLines){
        if(!(textarea instanceof $)) return; /*JQuery is required*/
        if(isNaN(maxLines) || !isFinite(maxLines) || maxLines == 0) return;
        var areaWidth = textarea.width();
        var oldHeight = textarea.css("height");
        var oldOverflow = textarea.css("overflow-y");
        var lineHeight = parseFloat(textarea.css("line-height"));
        var maxTxtHeight = maxLines*lineHeight + "px";

        /*Calculations for an efficient determination*/
        var fontstyles = "font-size:"+textarea.css("font-size");
        fontstyles += ";font-family:"+textarea.css("font-family");
        fontstyles += ";font-weight:"+textarea.css("font-weight");
        fontstyles += ";font-style:"+textarea.css("font-style");
        fontstyles += ";font-variant:"+textarea.css("font-variant");
        var wordWidth = wordWidthMappers[fontstyles];
        if(!wordWidth){
            var span = document.createElement("span");
            span.style.cssText = fontstyles+";display:inline;width:auto;min-width:0;padding:0;margin:0;border:none;";
            span.innerHTML = "W"; //Widest character
            document.body.appendChild(span);
            wordWidth = wordWidthMappers[fontstyles] = $(span).width();
            document.body.removeChild(span);
        }

        textarea = textarea[0];
        var temparea = textarea.cloneNode(false);
        temparea.style.visibility = "hidden";
        temparea.style.height = maxTxtHeight;
        temparea.value = textarea.value;
        document.body.appendChild(temparea);
        /*Math.round is necessary, to deal with browser-specific interpretations
          of height*/
        if(Math.round(temparea.scrollHeight/lineHeight) > maxLines){
            textarea.value = "";
            textarea.style.visibility = "hidden";
            if(oldOverflow != "scroll") textarea.style.overflowY = "hidden";
            textarea.style.height = maxTxtHeight;
            var i = 0;
            var textlen = temparea.value.length;
            var chars_per_line = Math.floor(areaWidth/wordWidth);
            while(i <= textlen){
                var curLines = Math.round(textarea.scrollHeight/lineHeight);
                if(curLines <= maxLines){
                    var str_to_add = temparea.value.substring(i, i+chars_per_line);
                    var nextLn = str_to_add.indexOf("\n");
                    if(nextLn > 0) str_to_add = str_to_add.substring(0, nextLn);
                    else if(nextLn == 0) str_to_add = "\n";
                    i += str_to_add.length;
                    textarea.value += str_to_add;
                } else if(curLines > maxLines){
                    textarea.value = textarea.value.substring(0, textarea.value.length-1);
                    i--;
                    if(Math.round(textarea.scrollHeight/lineHeight) <= maxLines) break;
                }
            }
            textarea.style.visibility = "visible";
            textarea.style.height = oldHeight;
            textarea.style.overflowY = oldOverflow;
        }
        temparea.parentNode.removeChild(temparea);
    }

    $(document).ready(function(){/* Add checker to the document */
        var tovalidate = $("#myTextarea");
        tovalidate.keyup(function(){
            /*Add keyup event handler. Optionally: onchange*/
            checkHeight(tovalidate, 3);
        });
    });
})();

这篇关于给定一个textarea,是否有一种方法来限制基于#行的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆