首页 > 其他分享 >CSS & JS Effect – Textarea Autoresize

CSS & JS Effect – Textarea Autoresize

时间:2022-11-05 14:24:03浏览次数:69  
标签:Textarea textarea Effect height padding CSS Autoresize border scrollHeight

前言

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

 

参考

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)

 

标签:Textarea,textarea,Effect,height,padding,CSS,Autoresize,border,scrollHeight
From: https://www.cnblogs.com/keatkeat/p/16860099.html

相关文章