1、textarea:

核心想法: ​​$(this).height(this.scrollHeight)​

  $textarea.addEventListener('input', function () {
var currentLength = this.value.length;
if (currentLength < lastLength) {
this.style.height = 'auto';
}
var currentLength = this.scrollHeight;

if (lastHeight !== currentHeight || !this.style.height) {
this.style.height = currentHeight + 2 + 'px';
}

lastLength = currentLength;
lastHeight = currentHeight;
})


这个方法在ios上会变得非常奇怪,因为我们使用input进行监听输入的时候,事实上他会把还没输入到屏幕上的文字还在输入法上的文字也计算在里边,所以使用input进行监听是非常不妥当的,事实上有一个方法能够监听中文的输入,但仅仅是中文的输入,​​compositionend​​能够监听中文的输入,没选中文的输入不会进行监听。ios出现问题就是每次设置​​auto​​,一旦我们输入的内容超过键盘,ios就会不断闪频。目前没找到解决的方法,我看作文纸条这个app上是实现了这个功能,但是他是使用的原生来实现的。这个方法舍弃。

2、占位符
  <div class="container">
<span id="text" class="text font-style"></span>
<textarea id="textarea" class="textarea font-style"></textarea>
</div>
  .container {
position: relative;
min-height: 90px;
}

.text {
font-size: 0;
color: transparent;
white-space: pre-wrap;
}

.textarea {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
resize: none;
border: 0;
outline: none;
}

/* 统一内容样式 */
.font-style {
font-family: Helvetica;
word-wrap: break-word;
word-break: break-all;
line-height: 48px;
font-size: 32px;
}


摘自[[贝聊科技]不简单的自适应高度输入框](​​https://juejin.im/post/5b7653...​​,所以那段时间疯狂在网上找解决方法。这是一种方法,但是这个方法是有问题的,如果我们要给输入的东西加上背景,比如说给textarea加上一个背景,然后问题就出现了,因为span是行内元素,背景能够到达的位置是span输入的内容范围,如果是内容少还好,内容多就炸了,一行中有一部分是没有背景颜色的。

3、偏移的方法
  <div class="placeholder"></div>
<textarea id="textarea"></textarea>
  .placeholder {
width: 100px;
line-height: 20px;
font-size: 20px;
transform: translateX(-1000px);
}
#textarea {
width: 100px;
line-height: 20px;
font-size: 20px;
}
  $textarea.on('input', function () {
var text = this.value;
$placeholder.innerText = text;
var height = $placeholder.style.height;
this.height = height + 'px';
})


这种方法就是把textarea和div的样式设置成完全一样,必须完全一样,然后把div的偏移量设置特别大,但是不能够设置div为​​display: none​​,这样我们就获取不到他的高度了,随便你怎么设置,只要隐藏这个东西就好了。

4、contenteditable

还有一种方法是把div变为可编辑的状态,但是这种方法一来就被我放弃了,因为要兼容多种机型,可能有的机型不兼容,而且要输入的字数,那就炸了,他使用的很少见的​​DOMNodeInserted​​,这不炸了嘛。

这几种方法在安卓上都还可以,但是在ios都炸了,我想贝聊的这位兄弟应该是没尝试输入很多文字,一旦输入很多文字,内容超过键盘,第一种方法就出现闪频,第二种方法直接文字都不见了,第三种方法pc端还能接受,但是移动端有些卡顿,文字一多,就直接炸了。反正一旦文字输多了,ios各种情况就开始出现了。所以我总结的经验的就是对高度自适应的输入框说不,这个需求做不了,没法做。客户端应该是可以做的,因为我看到作文纸条这个app是实现了这个功能的。