メッセージアプリみたいに現在見えている要素が見えたまま要素を上に追加させていく

追加した要素の高さだけscrollさせればメッセージアプリみたいな挙動を実現できます。

mygif

Code


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example prepend</title>
  </head>
  <body>
    <ul id="container"></ul>
  </body>


  <script>
  var cnt =0;
  


  window.onscroll = function(e){
    e.preventDefault();
    var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop
    //ページトップにスクロールした場合に要素を追加
    if (scrollTop === -1){
        prepend();
    }

  }

 

  var append = function(){
    var parent  = document.getElementById('container');
    for (var j = 20; j > 0;j --){
      cnt += 1;
      let child = document.createElement("li");
      child.innerHTML = 'cnt:' + j;
      child.id = 'cnt-' +j;
      let css = {
        background: 'lightblue',
        color: 'white',
        textAlign : 'center',
        height: '50px'
      };
      let keys = Object.keys(css);
      for(var i = 0;i < keys.length;i++){
        let key = keys[i];
        let val = css[key];
        child['style'][key] = val;
      }
      parent.insertBefore(child)
    }
  }

  var prepend = function(){
    alert('prepend');
    var pos = 0;
    var lastPos ;

    var parent  = document.getElementById('container');
    //lastElement: prepend()が呼ばれた時点での最新の要素
    //lastElementを起点にスクロール量を計算していく
    var lastElement = document.getElementById('cnt-'+cnt);

    if (lastElement){
      var rect = lastElement.getBoundingClientRect();
      lastPos = rect.top;
    }


    for (var j = 0; j < 20;j ++){
      cnt += 1;
      let child = document.createElement("li");
      child.innerHTML = 'cnt:' + cnt;
      child.id = 'cnt-' +cnt;
      let css = {
        background: 'lightblue',
        color: 'white',
        textAlign : 'center',
        height: '50px'
      };
      let keys = Object.keys(css);
      for(var i = 0;i < keys.length;i++){
        let key = keys[i];
        let val = css[key];
        child['style'][key] = val;
      }
      parent.insertBefore(child, parent.firstChild)
      let height = child.offsetHeight;
      lastPos += height;
    }

    window.scroll(0,lastPos);


  }

  append();
  </script>
</html>


Related Contents

Pickup Contents