LoginSignup
76
68

More than 5 years have passed since last update.

overflow:scroll/auto; を指定した要素の中身を一番下までスクロールする

Posted at

概要

LINEのようなUIで、発言のたびに自動的にスクロールを進めたい、という要件を満たします。

実装

#targetの中にどんどん発言が増えていくというイメージです。
なお、前の投稿「position:absolute; で top と bottom の両方を効かせる」のコードを使っています。

sample.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
  <style type="text/css">
  html,body {
    padding: 0;
    margin: 0;
    height: 100%;
    width: 100%;
  }

  header {
    position: absolute;
    top: 0;
    height: 20px;
    width: 100%;
    border: solid thin blue;
  }
  footer {
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: solid thin green;
  }

  #target {
    position: absolute;
    top: 20px;
    bottom: 30px;
    border: solid thin red;
    width: 100%;
    overflow: auto;
  }

  #target p {
    padding: 15px;
    margin: 10px;
    border: solid thin lightgreen;
    border-radius: 5px;
  }

  </style>
</head>
<body>
  <header>header</header>
  <div id="target">
  </div>
  <footer><button id="add">add</button></footer>

<script>
  var num = 0;
  $('#add').on('click', function() {
    $('#target').append('<p>' + (num++) + '</p>');

    // 一番下までスクロールする
    $('#target').animate({scrollTop: $('#target')[0].scrollHeight}, 'fast');
  });
</script>
</body>
</html>

CSSが長すぎますが、大事なのはscriptの最終行です。

76
68
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
76
68