textarea 内容自适应,高度向上扩展

效果:

原理:

监听 textarea 的 input 事件的 scrollHeight 变化(scrollHeight 元素内容高度),赋值给 height。

再给 textarea 设置最大最小高度,padding 为 0(它自身的),保证上下限。

代码:

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
    <style>
      body {
        margin: 0;
      }
      .wrapper {
        height: 100vh;
        display: flex;
        flex-direction: column;
        color: white;
      }
      nav {
        height: 60px;
        background-color: blue;
        position: fixed;
        width: 100%;
      }
      main {
        margin-top: 60px;
        background-color: pink;
        height: 100%;
        flex: 1;
      }

      footer {
        background-color: red;
        width: 100%;
        display: flex;
      }

      textarea {
        min-height: 50px;
        max-height: 300px;
        padding: 0;
        width: 100%;
      }
    style>
  head>
  <body>
    <div class="wrapper">
      <nav>navnav>
      <main>mainmain>
      <footer>
        <textarea>textarea>
      footer>
    div>
    <script>
      var textarea = document.querySelector("textarea");

      textarea.addEventListener("input", (e) => {
        textarea.style.height = 50 + "px"; // 删除文本内容,调整高度
        textarea.style.height = e.target.scrollHeight + "px";
      });
    script>
  body>
html>

你可能感兴趣的:(前端,css,javascript,前端)