scrollHeight、scrollTop、clientHeight浏览器兼容问题

快乐打工仔 分类:实例代码

本章节介绍一下标题中的几个属性的兼容性问题,需要的朋友可以做一下参考。

DTD已声明:

IE浏览器(准确的说是低版本IE浏览器):

document.documentElement.scrollHeight  浏览器所有内容高度 ,document.body.scrollHeight  浏览器所有内容高度
document.documentElement.scrollTop  浏览器滚动部分高度,document.body.scrollTop 始终为0
document.documentElement.clientHeight  浏览器可视部分高度,document.body.clientHeight  浏览器所有内容高度

FF浏览器:

document.documentElement.scrollHeight  浏览器所有内容高度 ,document.body.scrollHeight  浏览器所有内容高度
document.documentElement.scrollTop  浏览器滚动部分高度,document.body.scrollTop 始终为0
document.documentElement.clientHeight 浏览器可视部分高度,document.body.clientHeight  浏览器所有内容高度

谷歌浏览器:

document.documentElement.scrollHeight  浏览器所有内容高度, document.body.scrollHeight  浏览器所有内容高度
document.documentElement.scrollTop 始终为0,document.body.scrollTop  浏览器滚动部分高度
document.documentElement.clientHeight  浏览器可视部分高度,document.body.clientHeight  浏览器所有内容高度

DTD未声明:

IE浏览器(准确的说是低版本IE浏览器):

document.documentElement.scrollHeight  浏览器可视部分高度,document.body.scrollHeight  浏览器所有内容高度 
document.documentElement.scrollTop 始终为0,document.body.scrollTop  浏览器滚动部分高度
document.documentElement.clientHeight 始终为0,document.body.clientHeight  浏览器可视部分高度

FF浏览器:

document.documentElement.scrollHeight  浏览器可视部分高度, document.body.scrollHeight 浏览器所有内容高度
document.documentElement.scrollTop 始终为0,document.body.scrollTop 浏览器滚动部分高度
document.documentElement.clientHeight 浏览器所有内容高度,document.body.clientHeight 浏览器可视部分高度

谷歌浏览器:

document.documentElement.scrollHeight 浏览器可视部分高度,document.body.scrollHeight 浏览器所有内容高度
document.documentElement.scrollTop 始终为0,document.body.scrollTop 浏览器滚动部分高度
document.documentElement.clientHeight 浏览器所有内容高度,document.body.clientHeight 浏览器可视部分高度

相关知识说明:

浏览器所有内容高度即浏览器整个框架的高度,包括滚动条卷去部分+可视部分+底部隐藏部分的高度总和

浏览器滚动部分高度即滚动条卷去部分高度即可视顶端距离整个对象顶端的高度。

最后总结:

1、document.documentElement.scrollTop和document.body.scrollTop始终有一个为0,所以可以用这两个的和来求scrollTop

2、scrollHeight、clientHeight 在DTD已声明的情况下用documentElement,未声明的情况下用body

所以,判断滚动条是否已拉到页面最底部,可以用如下代码:

window.onscroll  = function (){
  var marginBot = 0;
  if (document.compatMode === "CSS1Compat"){
    marginBot = document.documentElement.scrollHeight 
        - (document.documentElement.scrollTop+document.body.scrollTop)
        -  document.documentElement.clientHeight;
  } 
  else {
    marginBot = document.body.scrollHeight 
        - document.body.scrollTop
        -  document.body.clientHeight;
  }
  if(marginBot<=0) {
    //do something        
  }
}

回复

我来回复
  • 暂无回复内容