Javascript 显示所有 textarea 行而不滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30050605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:34:01  来源:igfitidea点击:

display all textarea rows without scrolling

javascripthtmlcss

提问by mcmwhfy

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.

如何显示所有 textarea 行而不是垂直滚动。我已经尝试使用 css 使用 min-height 和 max-height 和 height: auto 但不起作用。

.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.

我真的不知道是否可以用 css 做到这一点。

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

也许使用原生 javascript 是可能的,所以我正在尝试这样的事情

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

I find something nice herebut it only increase and decrease rows , so how can I display all textarea rows without using scroll. DON'T NEED SOLUTION WITH FIXED HEIGHT, NEED SOMETHING DYNAMIC or other solutions that works only on chrome browser or only on firefox like Object.observe().

在这里找到了一些不错的东西但它只会增加和减少行,所以如何在不使用滚动的情况下显示所有 textarea 行。不需要固定高度的解决方案,需要一些动态的解决方案或其他仅适用于 chrome 浏览器或仅适用于像 Object.observe() 这样的 firefox 的解决方案。

Demo

演示

function expandtext(expand) {
  while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
    console.log("display all rows!") >
  }
}
body {
  padding: 20px;
}
.form-control {
  width: 400px;
  min-height: 100px;
  max-height: 900px;
  height: auto;
}
<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>

External JSFiddle.

外部JSFiddle

回答by ketan

Simple jQuery solution is:

简单的 jQuery 解决方案是:

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

Check Fiddle.

检查小提琴。

As you need a plain JavaScript solution, use following script that was created by User panzi. You can view the original answer here.

由于您需要一个普通的 JavaScript 解决方案,请使用以下由用户 panzi创建的脚本。您可以在此处查看原始答案。

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();
}

Check Fiddle Here.

在这里检查小提琴。

回答by Rounin

No Javascript required.

不需要Javascript。

You can display a no-scroll (ie. automatically re-sizing) editable text area with the following HTML and CSS:

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

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

回答by Mr. Polywhirl

The Mozilla Developer Network has an Autogrowing textarea exampleon their HTMLTextAreaElementpage. You should definitely check this out if you want to stay away from CSS3 solutions that can break on older browsers.

Mozilla 开发者网络在他们的页面上有一个自动增长的文本区域示例HTMLTextAreaElement。如果您想远离可能在旧浏览器上崩溃的 CSS3 解决方案,您绝对应该检查一下。

Here is the code from the example.

这是示例中的代码。

The following example shows how to make a textarea really autogrow while typing.

以下示例显示了如何在键入时使 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

自动调整

This example will take care of the case where you remove lines.

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

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>

回答by man_luck

Using Jquery and some logic I have tried to do what you need. Here is the jsfiddle; https://jsfiddle.net/45zsdzds/

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

HTML:

HTML:

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

Javascript:

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:

CSS:

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

Used How to get the number of lines in a textarea?to add a String prototype inorder to get the linecount.

使用如何获取文本区域中的行数?添加一个字符串原型以获取行数。