移动端:对高度自适应的输入框说不~

一、textarea:

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

$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上是实现了这个功能,可是他是使用的原生来实现的。这个方法舍弃。html

二、占位符

<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输入的内容范围,若是是内容少还好,内容多就炸了,一行中有一部分是没有背景颜色的。java

三、偏移的方法

<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,这样咱们就获取不到他的高度了,随便你怎么设置,只要隐藏这个东西就行了。ios

四、contenteditable

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

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

相关文章
相关标签/搜索