2010-06-01 134 views
2

如何使用jQuery在其內容(如Facebook中)中自動調整大小<textarea>textarea在jquery中自動調整大小

+1

自動調整大小?包含元素?窗戶?文本的長度? – 2010-06-01 10:46:54

+0

我認爲你的意思是像默認的Safari/Chrome textarea ...或Facebook上越來越多的textarea? – scunliffe 2010-06-01 10:49:02

+0

就像臉書 我想調整我的文本框的大小,當我在文本框中輸入更多的文字 – picnic4u 2010-06-01 10:53:40

回答

2
<script type="text/javascript"> 

    function adjustTextarea(this_){ 

    var value_ = this_.value; 

    value_ = value_.replace(new RegExp("\n\r", 'gi'), "\n"); 
    value_ = value_.replace(new RegExp("\r", 'gi'), "\n"); 

    var split_ = value_.split("\n"); 
    this_.rows = split_.length; 

    return; 
    } 

    </script> 

    <textarea cols="100" style="overflow:hidden;" onkeyup="adjustTextarea(this);" onfocus="adjustTextarea(this);" > 
    Text 
    </textarea> 
+0

純JavaScript的絕佳解決方案! – B4NZ41 2014-03-18 16:21:21

0

使用詹姆斯Padolsey自動調整jQuery插件從http://james.padolsey.com/javascript/jquery-plugin-autoresize/

基本用法

$('textarea#comment').autoResize({ 
     // On resize: 
     onResize : function() { 
     $(this).css({opacity:0.8}); 
     }, 
     // After resize: 
     animateCallback : function() { 
     $(this).css({opacity:1}); 
     }, 
     // Quite slow animation: 
     animateDuration : 300, 
     // More extra space: 
     extraSpace : 40 
    }); 
0

超輕:

有沒有人認爲contented?沒有搞亂滾動,只有我喜歡它的JS是如果你打算將數據保存在模糊上...顯然,它在所有流行的瀏覽器兼容:http://caniuse.com/#feat=contenteditable

只是它的樣式它看起來就像一個文本框,它會自動調整大小......使其最小高度成爲首選文本高度並且具有它。

這種方法最酷的是你可以在某些瀏覽器上保存和標記。根據什麼

http://jsfiddle.net/gbutiri/v31o8xfo/

<style> 
.autoheight { 
    min-height: 16px; 
    font-size: 16px; 
    margin: 0; 
    padding: 10px; 
    font-family: Arial; 
    line-height: 16px; 
    box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    overflow: hidden; 
    resize: none; 
    border: 1px solid #ccc; 
    outline: none; 
    width: 200px; 
} 
</style> 
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
<script> 
$(document).on('blur','.autoheight',function(e) { 
    var $this = $(this); 
    // The text is here. Do whatever you want with it. 
    console.log($this.html()); 
}); 

</script> 
<div class="autoheight contenteditable" contenteditable="true">Mickey <b>Mouse</b></div>