display all textarea rows without scrolling

时间:2015-05-05 10:34:32

标签: javascript html css

How can I display all textarea rows instead of having that vertical scroll. I have tried with css using min-height and max-height and height: auto but is not working.

.form-control{
    width:400px;
    min-height: 100px;
    max-height: 900px;
    height: auto;}

I don't really know if is possible to do that with css.

Maybe is possible with native javascript so I am trying something like this

function expandtext(expand) {
    while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
        console.log("display all rows!")>
    }
}

I find something nice here ,但它只会增加和减少行数,所以如何我可以显示所有textarea行而不使用滚动。不需要固定高度的解决方案,需要动态或其他仅适用于Chrome浏览器的解决方案或仅适用于像Object.observe()这样的firefox。

演示

&#13;
&#13;
function expandtext(expand) {
  while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
    console.log("display all rows!") >
  }
}
&#13;
body {
  padding: 20px;
}
.form-control {
  width: 400px;
  min-height: 100px;
  max-height: 900px;
  height: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class=" form-group">
  <label>remove texarea scroll and display all rows</label>
  <textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum
    primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet
    tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>
</div>
<div class=" form-group">
  <label>remove texarea scroll and display all rows</label>
  <textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut.</textarea>
</div>
&#13;
&#13;
&#13;

外部JSFiddle

4 个答案:

答案 0 :(得分:7)

简单的jQuery解决方案是:

$(function() {
    $('textarea').each(function() {
        $(this).height($(this).prop('scrollHeight'));
    });
});

检查Fiddle.

由于您需要简单的JavaScript解决方案,请使用User panzi创建的以下脚本。您可以查看原始答案here

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);
    };
}
function init () {
    var text = document.getElementById('textarea');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 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();
}

检查Fiddle Here.

答案 1 :(得分:5)

无需Javascript。

您可以使用以下HTML和CSS显示无滚动(即自动重新调整大小)的可编辑文本区域:

.textarea {
width:250px;
min-height:50px;
height:auto;
border:2px solid rgba(63,63,63,1);}
<div class="textarea" contenteditable="true">

答案 2 :(得分:2)

Mozilla开发者网络在HTMLTextAreaElement页面上有一个Autogrowing textarea example。如果你想远离可能在旧浏览器上破坏的CSS3解决方案,你一定要检查一下。

以下是示例中的代码。

  

以下示例显示了如何在键入时使textarea真正自动增长。

function autoGrow(oField) {
  if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = oField.scrollHeight + "px";
  }
}
textarea.noscrollbars {
  overflow: hidden;
  width: 300px;
  height: 100px;
}
<form name="myForm">
  <fieldset>
    <legend>Your comments</legend>
    <p>
      <textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea>
    </p>
    <p>
      <input type="submit" value="Send" />
    </p>
  </fieldset>
</form>

其autoAdjust

此示例将处理删除行的情况。

function autoAdjustTextArea(o) {
  o.style.height = '1px'; // Prevent height from growing when deleting lines.
  o.style.height = o.scrollHeight + 'px';
}


// =============================== IGNORE =====================================
// You can ignore this, this is for generating the random characters above.
var chars = '\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var randRange=function(min,max){return max==null?randRange(0,min):~~(Math.random()*(max-min)+min);}
var randChars=function(chrs,len){return len>0?chrs[randRange(chrs.length)]+randChars(chrs,len-1):'';}
// ============================== /IGNORE =====================================


// Get a reference to the text area.
var txtAra = document.getElementsByClassName('noscrollbars')[0];
// Generate some random characters of length between 150 and 300.
txtAra.value = randChars(chars,randRange(150,300));
// Trigger the event.
autoAdjustTextArea(txtAra);
textarea.noscrollbars {
  overflow: hidden;
  width: 400px; /** This is via your example. */
}
<form name="myForm">
  <fieldset>
    <legend>Your comments</legend>
    <p>
      <textarea class="noscrollbars" onkeyup="autoAdjustTextArea(this);"></textarea>
    </p>
    <p>
      <input type="submit" value="Send" />
    </p>
  </fieldset>
</form>

答案 3 :(得分:1)

使用Jquery和一些逻辑,我试图做你需要的。 这是jsfiddle; https://jsfiddle.net/45zsdzds/

HTML:

<textarea class="myClass" id="FurnishingDetails" name="FurnishingDetails" id="FurnishingDetails"></textarea>

使用Javascript:

$('#FurnishingDetails').text('hello\nhello1\nhello2\nhello3\nhello4\nhello5');
String.prototype.lines = function() { return $('#FurnishingDetails').text().split(/\r*\n/); }
String.prototype.lineCount = function() { return $('#FurnishingDetails').text().lines().length; }
$('#FurnishingDetails').css('height', ($('#FurnishingDetails').text().lineCount() + 1) + 'em');

CSS:

textarea[name='FurnishingDetails']{
 height:2em;  
}

使用How to get the number of lines in a textarea?添加String原型以获取行数。