开发者

textbox auto expandable

开发者 https://www.devze.com 2023-01-01 17:02 出处:网络
ho开发者_StackOverflow中文版w can i make textbox auto expandable through javascriptYou could compare the count of your value with the rows * cols. I dont really know how many letters there are in a co

ho开发者_StackOverflow中文版w can i make textbox auto expandable through javascript


You could compare the count of your value with the rows * cols. I dont really know how many letters there are in a col in html but if you tested that you could do something like:

var colCount =  document.yourForm.yourTextArea.cols;
var rowCount =  document.yourForm.yourTextArea.rows;
if((colCount * numberOfLettersInACol) * rowCount) <= document.yourForm.yourTextArea.value.length){
    document.yourForm.yourTextArea.rows = rowCount + 1;
}


I suggest using a javascript library such as jQuery and then using a plugin such as this one:

http://james.padolsey.com/javascript/jquery-plugin-autoresize/


Give the textarea an ID of "textarea-expand" and try this:
Note: This does not 'reshrink' when you delete the text - it only expands
Edit: (now works without jquery)
Edit: online demo at http://bit.ly/aOik0B

<script type="text/javascript">

// ---------- FitToContent ----------

var maxHeight;

function fitToContent(idSelector) {

 var text = idSelector && idSelector.style ? idSelector : document.getElementById(idSelector);
    if ( !text ) {
      return;
 }

 function adjustHeight(idSelector, maxHeight) {
    var adjustedHeight = text.clientHeight;
    if ( !maxHeight || maxHeight > adjustedHeight ) {
        adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
        if ( maxHeight ) {
           adjustedHeight = Math.min(maxHeight, adjustedHeight);
        }
        if ( adjustedHeight > text.clientHeight ) {
           text.style.height = adjustedHeight + "px";
        }
    }
  }

  adjustHeight(text, document.documentElement.clientHeight);

}

window.onload=function(){
    function init(){
        fitToContent("textarea-expand");
    }
    init();
    document.getElementById("textarea-expand").onkeypress = init
};

</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消