聊天窗口内容滚动到底部的方法scrollTop和scrollIntoView

测试内容样式:

<style type="text/css">
     #container{
	overflow-y:auto; 
	overflow-x:hidden; 
	height:150px;
	border:1px solid red;
         width:350px;
	}
      html,body{margin:0px;padding:0px;font-family: "微软雅黑";}
</style>
<div id="container">
  <ul id="msgList" >
    <li>111111111</li>
    <li>2222222222</li>
    <li>333333333</li>
    <li>4444444444</li>
    <li>5555555555</li>
    <li>66666666666</li>
    <li>77777777777</li>
  </ul>
</div>
<div class="footer">
    <textarea  id='msgInput' rows="2" placeholder="输入点什么" class="msg-input"></textarea>
    <input type="button" class="btn" id='btnSubmit'value="发送" οnclick="" type="reset">
</div>

1、第一种方法:scrollTop() 方法返回或设置匹配元素的滚动条的垂直位置。

<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
//一进来就滚动到底部
$("#container").scrollTop($("#container")[0].scrollHeight);
$("#btnSubmit").click(function(){
	//如果没有内容就return
	var txtVal=$("#msgInput").val();
    // alert(txtVal);
    if(txtVal==''){
       return false;
    }
	//有内容继续
	$('#msgList').append('<li>'+txtVal+'</li>');
        $("#container").scrollTop($("#container")[0].scrollHeight);
  })
</script>

浏览器兼容:

var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;


2、第二种方法:使用JS原生提供的Element.scrollIntoView()可以定位到指定元素的位置

<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
//进来的时候自动滚到底部
($('#msgList').children("li:last-child")[0]).scrollIntoView();
$("#btnSubmit").click(function(){
	//如果没有内容就return
	var txtVal=$("#msgInput").val();
    // alert(txtVal);
    if(txtVal==''){
       return false;
    }
	//有内容继续
	$('#msgList').append('<li>'+txtVal+'</li>');
    setTimeout(function () {
      ($('#msgList').children("li:last-child")[0]).scrollIntoView();
    },100);
  })
</script>

直接用:<li οnclick="javascript:document.getElementById('here').scrollIntoView()"></li>


发布了44 篇原创文章 · 获赞 23 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_14993375/article/details/79549923