何时使用offsetHeight,clientHeight和scrollHeight以及如何查找我们到达页面底部?

时间:2017-09-26 14:57:38

标签: javascript scroll

offsetHeightclientHeightscrollHeight之间有什么区别?

此外,当我们向下滚动时,如果发现页面底部是动态加载(延迟加载),如何找到我们到达页面底部?

1 个答案:

答案 0 :(得分:1)

offsetHeight:

以px为单位返回元素的高度。包括paddingscrollBarborder的高度,但 margin

clientHeight:

以px为单位返回元素的高度。包括padding scrollBarbordermargin

scrollHeight:

以px为单位返回元素的高度。包括paddingscrollBarbordermargin

同样适用于clientWidthoffsetWidthscrollWidth

中的宽度

这是一个小提琴:

function whatis(propType)
{
var mainDiv = document.getElementById("MainDIV");
if(window.sampleDiv==null){
	var div = document.createElement("div");
	window.sampleDiv = div;
}
div = window.sampleDiv;
var propTypeWidth = propType.toLowerCase()+"Width";
var propTypeHeight = propType+"Height";

var computedStyle = window.getComputedStyle(mainDiv, null);
var borderLeftWidth = computedStyle.getPropertyValue("border-left-width");
var borderTopWidth = computedStyle.getPropertyValue("border-top-width");

div.style.position = "absolute";
div.style.left = mainDiv.offsetLeft+Math.round(parseFloat((propType=="client")?borderLeftWidth:0))+"px";
div.style.top = mainDiv.offsetTop+Math.round(parseFloat((propType=="client")?borderTopWidth:0))+"px";
div.style.height = mainDiv[propTypeHeight]+"px";
div.style.lineHeight = mainDiv[propTypeHeight]+"px";
div.style.width = mainDiv[propTypeWidth]+"px";
div.style.textAlign = "center";
div.innerHTML = propTypeWidth + " X " + propTypeHeight + "( " +
    mainDiv[propTypeWidth] + " x "+ mainDiv[propTypeHeight] + " )";



div.style.background = "rgba(0,0,246,0.5)";
document.body.appendChild(div);

}
document.getElementById("offset").onclick = function(){whatis('offset');}
document.getElementById("client").onclick = function(){whatis('client');}
document.getElementById("scroll").onclick = function(){whatis('scroll');}
#MainDIV{
				border:5px solid red;
			}
<button id="offset">offsetHeight & offsetWidth</button>
<button id="client">clientHeight & clientWidth</button>
<button id="scroll">scrollHeight & scrollWidth</button>

<div id="MainDIV" style="margin:auto; height:200px; width:400px; overflow:auto;">
<div style="height:400px; width:500px; overflow:hidden;"></div>
</div>

小提琴复制自:http://jsfiddle.net/shibualexis/yVhgM/3/

使用上述功能知道我们到达页面底部可以这样做:

if((window.innerHeight + window.pageYOffset) >= document.body.scrollHeight )){
   //We reached bottom of page and there is no more vertical scroll can happen.
}

因此,这就是你可以进行垂直滚动的方法:

while(!(window.innerHeight + window.pageYOffset) >= document.body.scrollHeight )){
     window.scrollTo(0, document.body.scrollHeight);
}

此处条件(window.innerHeight + window.pageYOffset) >= document.body.scrollHeight )与浏览器无关,可以在Chrome,FF,IE和Safari上运行。