In the chat window, when the number of messages exceeds the height of the message window DIV, a scroll bar will appear, but at this time, the scroll bar is always located at the top of the DIV in most browsers, which will cause subsequent messages to be invisible. You have to drag the scroll bar down to see new messages, what if the scroll bar is always at the bottom of the DIV when the scroll bar appears?
Method 1: Set scrollTop=scrollHeight of DIV;
Method 2: Add a hidden element element at the bottom of the DIV, and then call element.scrollIntoView(). The scrollIntoView here is a native method, and it is not difficult to find that this method is used to scroll the element to the visible area by name.
Just put the two ways together for simplicity.
<head>
<style type="text/css">
div{margin:0px;padding:0px;}
#main{width:380px;height:102px;overflow-y:auto;border:1px solid #ddd ;padding:0 10px 0 10px;}
#content{width:350px;line-height:20px;}
</style>
<script type="text/javascript">
window.onload=function(){
var i=1;
var hid=document.getElementById('msg_end');//The element hidden under the message box
var btn=document.getElementById('btnSend');//Button for adding a message
var cont=document.getElementById('content') ;//Message box
var mai=document.getElementById('main');
btn.onclick=function(){
cont.innerHTML+='message content' +i+'<br/>';
//hid.scrollIntoView(false);//Mode 1 makes it visible by calling the scrollIntoView() method of the hidden element//mai.scrollTop=
mai.scrollHeight;//Mode 2 by setting the scroll height
i++;
}
}
</script >
</head>
<body>
<div id="main">
<div id="content"></div>
<span id="msg_end" style="overflow:hidden"></span>
</div >
<input type="button" id="btnSend" value="add"/>
</body>
</html>
The effect is as follows, the scroll bar is always at the bottom