内容超出容器滚动,并可滚动查看

要实现的功能与浏览器控制台console类似:消息的实时推送到前端展示,新消息展示在页面最后一条;数据超出容器可滚动,当拖动滚动条时,可以查看任意数据。
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  .box1 {
    border: 2px solid #ccc;
    overflow-y: scroll;
    height: 400px;
    width: 600px;
    margin: 0 auto;
  }
  .box1 p {
    height: 50px;
    padding: 0;
    margin: 0
  }
  </style>
</head>
<body>
    <div class="box1" id="box1">
    </div>  
  <script>
    let num = 0
    let isScroll = true
    let showContent1 = document.getElementById('box1')
    
    setInterval(function(){
      let p=document.createElement("p")
      num += 1
      p.innerHTML="我是第"+num+"条通道报文消息"
      showContent1.appendChild(p)
      if(isScroll) {
        showContent1.scrollTop = showContent1.scrollHeight
      }
    },500)
    showContent1.onscroll= function() {
      isScroll  = false
      let scrollTop = showContent1.scrollTop
      let clientHeight = showContent1.clientHeight
      let scrollHeight = showContent1.scrollHeight
      console.log(scrollTop,clientHeight,scrollHeight)
      // 避免没有数据的时候 重复执行 scrollHeight > clientHeight 
      if(scrollHeight > clientHeight  && scrollTop + clientHeight === scrollHeight) {
        showContent1.scrollTop = showContent1.scrollHeight
        isScroll  = true
      }
    }   
  </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。