纯CSS实现自动滚动到底部

发布于:2025-04-21 ⋅ 阅读:(84) ⋅ 点赞:(0)

 

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>自动滚动到底部</title>
    <style>
      * {
        box-sizing: border-box;
      }
      body {
        margin: 0;
        height: 100vh;
        display: flex;
        flex-direction: column;
      }
      .chater {
        flex: 1;
        overflow: auto;
        padding: 1em;
        display: flex;
        flex-direction: column-reverse;
      }
      .msger {
        flex: 1;
        display: flex;
        flex-direction: column;
      }
      .msger > pre {
        background-color: #eee;
        padding: 1em;
        border-radius: 8px;
        white-space: pre-wrap;
      }
      .msger .user {
        align-self: flex-end;
        margin-left: 10vw;
      }
      .msger .ai {
        align-self: flex-start;
        margin-right: 10vw;
      }
      .sender {
        flex-shrink: 0;
        padding: 1em;
      }
    </style>
  </head>
  <body>
    <div class="chater">
      <div class="msger"></div>
    </div>
    <div class="sender">
      <input type="text" />
      <button onclick="send()">发送</button>
    </div>
    <script>
      function send() {
        document.querySelector('.chater').scrollTop = document.querySelector('.chater').scrollHeight

        const pre = document.createElement('pre')
        pre.className = 'user'
        pre.textContent = document.querySelector('input').value
        document.querySelector('.msger').appendChild(pre)

        const pre2 = document.createElement('pre')
        pre2.className = 'ai'
        const timer = setInterval(() => {
          pre2.textContent +=
            String.fromCharCode(Math.floor(Math.random() * 122) + 65).repeat(
              Math.ceil(Math.random() * 10)
            ) + (Math.random() < 0.2 ? '\n' : ' ')
          if (pre2.textContent.length > 1000) clearInterval(timer)
        }, 50)
        document.querySelector('.msger').appendChild(pre2)
      }
    </script>
  </body>
</html>


网站公告

今日签到

点亮在社区的每一天
去签到