首先說一下常識:
網頁可見區域寬: document.body.clientWidth;
網頁可見區域高: document.body.clientHeight;
網頁可見區域寬: document.body.offsetWidth (包括邊線的寬);
網頁可見區域高: document.body.offsetHeight (包括邊線的寬);
網頁正文全文寬: document.body.scrollWidth;
網頁正文全文高: document.body.scrollHeight;
網頁被卷去的高: document.body.scrollTop;
網頁被卷去的左: document.body.scrollLeft;
網頁正文部分上: window.screenTop;
網頁正文部分左: window.screenLeft;
屏幕分辨率的高: window.screen.height;
屏幕分辨率的寬: window.screen.width;
屏幕可用工作區高度: window.screen.availHeight;
屏幕可用工作區寬度:window.screen.availWidth;
關於offset共有5個東西需要弄清楚:
1. offsetParent
2. offsetTop
3. offsetLeft
4. offsetWidth
5. offsetHeight
offsetWidth與offsetHeight
也就是元素的可視寬度,這個寬度包括元素的邊框(border),水平padding,垂直滾動條寬度,元素本身寬度等
offsetWidth=(border-width)*2+(padding-left)+(width)+(padding-right)。
offsetHeight=(border-width)*2+(padding-top)+(height)+(padding-bottom)
offsetLeft與offsetTop
返回對象元素邊界的左上角頂點相對於offsetParent的左上角頂點的水平偏移量。從這個定義中我們可以明確地知道offsetLeft與當前元素的margin-left和offsetParent的padding-left有關
offsetLeft=(offsetParent的padding-left)+(中間元素的offsetWidth)+(當前元素的margin-left)。
offsetTop=(offsetParent的padding-top)+(中間元素的offsetHeight)+(當前元素的margin-top)
offsetParent
- 如果當前元素的父級元素沒有進行CSS定位(position為absolute或relative),offsetParent為body。
- 如果當前元素的父級元素中有CSS定位(position為absolute或relative),offsetParent取最近的那個父級元素。
滾動條到底部的條件即為scrollTop + clientHeight == scrollHeight。
function getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//文檔的總高度
function getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
function getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = function(){
if(getScrollTop() + getWindowHeight() == getScrollHeight()){
alert("已經到最底部了!!");
}
};
//jquery
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if(scrollTop + windowHeight == scrollHeight){
alert("已經到最底部了!");
}
});
原文地址:https://www.cnblogs.com/yangwang12345/p/7798084.html