`
wangyanlong0107
  • 浏览: 480365 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

让DIV中的垂直滚动条自动滚到最底部

    博客分类:
  • js
阅读更多

在聊天窗口中当消息增多超过消息窗体DIV的高度时就会出现滚动条,但此时滚动条在绝大多数浏览器中都始终位于DIV的顶部,这样就会导致之后的消息看不见,必须往下拖动滚动条才能看到新的消息,如果做到当出现滚动条时,滚动条始终位于DIV的底部呢?

方式一:设置DIV的scrollTop=scrollHeight;

方式二:在DIV的底部添加一隐藏元素element,然后调用element.scrollIntoView()。这里的scrollIntoView是原生的方法,通过名称我们就不难发现该方法用来使元素滚动到可视区域。

为了简单起见直接将两种方式放在一起。

<html>
<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');//隐藏在消息框下面的元素
    var btn=document.getElementById('btnSend');//添加消息的按钮
    var cont=document.getElementById('content');//消息框
    var mai=document.getElementById('main');
    btn.onclick=function(){
        cont.innerHTML+='消息内容'+i+'<br/>';
        //hid.scrollIntoView(false);//方式1通过调用隐藏元素的scrollIntoView()方法使其可见
        //mai.scrollTop=mai.scrollHeight;//方式2通过设置滚动高度
        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="添加"/>
</body>
</html>
复制代码

效果如下,滚动条始终最底部

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics