js监听滚动条触底

<!DOCTYPE html>
<html>
<head>
	<title>index</title>
	<style type="text/css">
		.c{
			height: 200px;
			width: 80%;
			margin: 20px auto;
			background-color: #333;
			font-size: 24px;
			text-align: center;
			line-height: 200px;
			color: white;
		}
	</style>
</head>
<body>
	<h2>兼容IE是不可能的,这辈子都不可能~</h2>
	<div class="c">1</div>
	<div class="c">2</div>
	<div class="c">3</div>
	<div class="c">4</div>
	<div class="c">5</div>
	<div class="c">6</div>
</body>
</html>

<script type="text/javascript">

	var num = 6; // div文本

	window.onscroll = function(){
        //变量scrollTop是滚动条滚动时,距离顶部的距离
        var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
        //变量windowHeight是可视区的高度
        var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //变量scrollHeight是滚动条的总高度
        var scrollHeight = document.documentElement.scrollHeight||document.body.scrollHeight;
                   //滚动条到底部的条件
                   //一般来说需要提前触发:scrollTop+windowHeight + 200 >=scrollHeight
                   if(scrollTop+windowHeight>=scrollHeight){
                   	// 模拟加载新的数据
                   	var div = document.createElement("div");  // 创建div
					div.className = "c";   // 设置class
					div.innerHTML = ++num; // 填充文本
                    document.body.appendChild(div); // 将div添加到页面
            		console.log("已触底");
                  }  
        }

</script>

 

posted @ 2020-12-17 09:47  踏浪逐星岚  阅读(567)  评论(0)    收藏  举报