CSS & JS Effect – Textarea Autoresize

前言

这是一个很普遍的体验, 而且实现起来也很简单哦

 

参考

YouTube – How to Auto Resize Textarea using HTML CSS & JavaScript

 

效果

我故意加了 border 和 padding 来解释.

 

Step by Step 实现

HTML

<textarea class="stg-text-area-autoresize" rows="4"></textarea>

CSS Style

textarea {
  font-size: 1.5rem;
  padding-inline: 1rem;
  background-color: pink;
  border-inline: unset;
  outline: unset;

  // 我刻意加入 border padding 来让情况变得复杂
  padding-top: 15px;
  padding-bottom: 20px;
  border-top: 15px solid red;
  border-bottom: 20px solid red;
}

效果

JavaScript

const textarea = document.querySelector('textarea');
// 监听, 每一次 input 的时候看需不需要 resize
textarea.addEventListener('input', () => {
  // 先把 height 设置成 auto, 这样就可以还原小
  textarea.style.height = 'auto';

  // 获取当前的 border block
  const { borderTopWidth, borderBottomWidth } = window.getComputedStyle(textarea);

  // 在把 height 设置成 scrollHeight 让它变大
  // 之所以需要加 border 是因为 height 在 border-box 情况下是要包括 border 高度的.
  // 而 scrollHeight 只有到 padding 的高度
  textarea.style.height = `${
    textarea.scrollHeight + parseFloat(borderTopWidth) + parseFloat(borderBottomWidth)
  }px`;
});

关键就在改变 textare height

auto 变小

scrollHeight 变大

如果想了解 height, scrollHeight 是如何计算的, 可以看这篇: DOM – Dimension (offset, client, computed, rect)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章