要實現(xiàn)的功能與瀏覽器控制臺console類似:消息的實時推送到前端展示疗认,新消息展示在頁面最后一條完残;數(shù)據(jù)超出容器可滾動,當拖動滾動條時横漏,可以查看任意數(shù)據(jù)谨设。
<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)
// 避免沒有數(shù)據(jù)的時候 重復執(zhí)行 scrollHeight > clientHeight
if(scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
showContent1.scrollTop = showContent1.scrollHeight
isScroll = true
}
}
</script>
</body>
</html>
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者