使用原生js监听滚动条到达底部并加载一条内容

web网页判断滚动条是否到达底部

Document.onscroll

首先要用document的onscroll方法监听滚动条的变化

document.onsroll = function () {
		/******/
}

具体代码

最重要的是要通过document的scrollHeight 和 document的scrollTop来实现

代码:

	if (_container.scrollTop == (_container.scrollHeight - 640)) {
			 var div=document.createElement('div');
			 div.innerHTML = "ssss";
			_container.appendChild(div)
		}

完整html代码

	<!DOCTYPE html>
	<html>
		<head>
			<meta charset="utf-8" />
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title></title>
			 <style>
			  #container {
			    position: absolute;
			    height: auto;
			    top: 0;
			    bottom: 0;
			    width: auto;
			    left: 0;
			    right: 0;
			    overflow: auto;
			  }
			  
			  #foo {
			    height:1000px;
			    width:1000px;
			    
			    display: block;
			  }
			  
			  </style>
		</head>
		<body>
		    <div id="container">
		      <div id="foo">sssss</div>
		    </div>
		  
		    <script type="text/javascript">
				
		      //js绑定你需要监控滚动事件的dom,也可以绑定document.body监控整个网页滚动
		      //也可以监控具体的dom滚动,像下面的container Id对象
			  _container = document.getElementById('container');
		      _container.onscroll = function() {
				console.log(document.getElementById('container').scrollHeight + " " + _container.scrollTop)
		        if (_container.scrollTop == (_container.scrollHeight - 640)) {
					 var div=document.createElement('div');
					 div.innerHTML = "ssss";
					_container.appendChild(div)
				}
		      };
		    </script>
		  </body>
	</html>
发布了20 篇原创文章 · 获赞 5 · 访问量 2078

猜你喜欢

转载自blog.csdn.net/qq_42859887/article/details/103623730