Skip to content

Instantly share code, notes, and snippets.

@zhaoda
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhaoda/202b1ab8257f711f5e98 to your computer and use it in GitHub Desktop.
Save zhaoda/202b1ab8257f711f5e98 to your computer and use it in GitHub Desktop.
获取网页大小
// 网页上的每个元素,都有clientHeight和clientWidth属性,
// 这两个属性指元素的内容部分再加上padding的所占据的视觉面积,不包括border和滚动条占用的空间。
// 网页上的每个元素还有scrollHeight和scrollWidth属性,指包含滚动条在内的该元素的视觉面积。
// 大多数情况下,都是document.documentElement.clientWidth返回正确值。
// 但是,在IE6的quirks模式中,document.body.clientWidth返回正确的值,因此函数中加入了对文档模式的判断。
// 方案1
// 必须在页面加载完成后才能运行,否则document对象还没生成,浏览器会报错
// clientWidth和clientHeight都是只读属性,不能对它们赋值
function getViewport() {
if (document.compatMode == "BackCompat"){
eturn {
width: document.body.clientWidth,
height: document.body.clientHeight
}
} else {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}
}
// 方案2
// 如果网页内容能够在浏览器窗口中全部显示,不出现滚动条,那么网页的clientWidth和scrollWidth应该相等。
// 但是实际上,不同浏览器有不同的处理,这两个值未必相等。所以,我们需要取它们之中较大的那个值。
function getPagearea() {
if (document.compatMode == "BackCompat") {
return {
width: Math.max(document.body.scrollWidth, document.body.clientWidth),
height: Math.max(document.body.scrollHeight, document.body.clientHeight)
}
} else {
return {
width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment