2016-03-07 73 views
4

我已经确定textarea的高度根据其内容(而不是滚动)而改变。但默认的高度是32px而不是16px,我该如何改变它。动态文本区域高度

HTML:

<textarea id="cryTextArea" style="background:#fff; border:dashed #bc2122 1px; height:auto; width:100%;"></textarea> 

的Javascript/jQuery的:

var observe; 
if (window.attachEvent) { 
    observe = function(element, event, handler) { 
    element.attachEvent('on' + event, handler); 
    }; 
} else { 
    observe = function(element, event, handler) { 
    element.addEventListener(event, handler, false); 
    }; 
} 
var firstHeight = 0; 
var storeH = 0; 
var storeH2 = 0; 
function init() { 
    var text = document.getElementById('cryTextArea'); 

    function resize() { 
    //console.log(text.scrollHeight); 
    text.style.height = 'auto'; 
    if (storeH != text.scrollHeight) { 
     text.style.height = text.scrollHeight + 'px'; 
     storeH = text.scrollHeight; 
     if (storeH2 != storeH) { 
     console.log("SENT->" + storeH); 
     storeH2 = storeH; 
     } 
    } 
    } 
    /* 0-timeout to get the already changed text */ 
    function delayedResize() { 
    window.setTimeout(resize, 0); 
    } 
    observe(text, 'change', resize); 
    observe(text, 'cut', delayedResize); 
    observe(text, 'paste', delayedResize); 
    observe(text, 'drop', delayedResize); 
    observe(text, 'keydown', delayedResize); 

    text.focus(); 
    text.select(); 
    resize(); 
} 
init(); 

see fiddle

+1

您可以使用[textarea的自动调整大小](http://javierjulio.github.io/textarea-autosize/)或[flexibleArea(http://flaviusmatis.github.io/flexibleArea.js /)或[jQuery .elastic()](http://stackoverflow.com/questions/17772260/textarea-auto-height) – MKAD

回答

3

假设我的理解正确你的textarea默认显示2行,你只想显示一行。您的HTML中的 您可以定义要显示的行数。就像这样:

<textarea id="cryTextArea" rows=1 style="background:#fff; border:dashed #bc2122 1px; height:auto; width:100%;"></textarea> 
+0

我曾尝试过'rows =“1”'......哈哈 – maxisme

0

试试这个:LINK

<html> 
    <head> 
    <script> 
    function textAreaAdjust(o) { 
     o.style.height = "1px"; 
     o.style.height = (25+o.scrollHeight)+"px"; 
    } 
    </script> 
    </head> 
    <body> 
    <textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea> 
    </body> 
    </html> 
+1

你应该帮助人们找到解决方案,而不仅仅是[COPY AND PASTE FROM OTHER](http: //stackoverflow.com/questions/995168/textarea-to-resize-based-on-content-length) – MKAD

+1

至少为原帖提供了点数。 –

+0

好吧,让我在将来发布帖子并更新帖子链接 –