聊天窗口内容滚动到底部的方法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>


  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值