/*
document.body是为了兼容chrome浏览器
*/
//获取到滚动条距可视页面顶部的位置
function getScrollTop(){
var scrollTop = 0;
//经测试,在chrome和ff下,document.documentElement.scrollTop并没有什么卵用,都是一直返回0。但在IE下是好使的,可怜的IE。
if(document.documentElement && document.documentElement.scrollTop){
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop
}
return scrollTop;
}
//获取当前可视范围高度
function getClientHeight(){
var clientHeight = 0;
if(document.body.clientHeight && document.documentElement.clientHeight){
clientHeight = Math.min(document.body.clientHeight,document.documentElement.clientHeight);
} else{
clientHeight = Math.max(document.body.clientHeight,document.documentElement.clientHeight);
}
return clientHeight;
}
//获取文档完整高度
function getScrollHeight(){
return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
}
/*
经过测试发现,chrome浏览器的document.body.scrollHeight==document.documentElement.scrollHeight
*/
利用上面这三个方法,结合window.onscroll事件,就可以简单实现一下网页拖到底部时自动添加内容或别的东西的方法。
window.onscroll = function(){
var scrollTop = getScrollTop();
var clientHeight = getClientHeight();
var scrollHeight = getScrollHeight();
if(scrollTop+clientHeight == scrollHeight){
alert("到达底部");
//ajax请求数据然后加到内容中去
}