美文网首页
内容超出容器滚动,并可滚动查看

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

作者: 书到用时才恨少 | 来源:发表于2020-03-24 21:40 被阅读0次
    要实现的功能与浏览器控制台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>
    

    相关文章

      网友评论

          本文标题:内容超出容器滚动,并可滚动查看

          本文链接:https://www.haomeiwen.com/subject/mfaayhtx.html