要实现的功能与浏览器控制台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>
网友评论