1. 程式人生 > >textarea輸入框隨內容撐開高度

textarea輸入框隨內容撐開高度

方法一(jquery):

$('textarea').each(function () {
  this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
});

方法二:

function setHeight(element) {
  $(element).css({'height':'auto','overflow-y':'hidden'}).height(element.scrollHeight);
}
$('textarea').each(function () {
  setHeight(this);
}).on('input', function () {
  setHeight(this);
});

方法三(在vue專案中使用):

HTML:

<div class="textarea-wrapper">
  <div class="content-editable" contenteditable="true">{{deliveryLocation}}</div>
  <textarea v-model="deliveryLocation" @change="trimSpacesAndUppercase($event, 'deliveryLocation')" class="field-textarea" placeholder="請輸入詳細地址"></textarea>
</div>

CSS:

.textarea-wrapper {
  position: relative;
  display: block;
  width: 100%;
  padding: .1rem 0;
  .content-editable {
    position: relative;
    z-index: -1;
    opacity: 0;
    display: block;
    width: 100%;
    line-height: normal;
    font-size: .27rem;
    color: #999;
    white-space: pre;
  }
  .field-textarea {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: .1rem 0;
    line-height: normal;
    font-size: .27rem;
    color: #464545;
    text-align: left;
    resize: none;
    overflow: hidden;
    background-color: transparent;
    &::-webkit-input-placeholder {
      text-align: left;
      font-size: .27rem;
      color: #999;
    }
  }
}