各個瀏覽器對獲取獲取窗口滾動條位置和窗口大小沒有提供統一的API,以下是對其封裝,解決兼容性問題
/**
* 獲取瀏覽器視口的大小(顯示文檔的部分)
*
*/
function getViewPortSize(){
// 除IE8及更早的版本以外的瀏覽器
if( window.innerWidth != null ){
return {
w : window.innerWidth,
h : window.innerHeight
}
}
// 標准模式下的IE
if( document.compatMode == "css1Compat" ){
return {
w : document.documentElement.clientWidth,
h : document.documentElement.clientHeight
}
}
// 怪異模式下的瀏覽器
return {
w : document.body.clientWidth,
h : document.body.clientHeight
}
}
/**
* 獲取窗口滾動條的位置
*/
function getScrollOffset(){
// 除IE8及更早版本
if( window.pageXOffset != null ){
return {
x : window.pageXOffset,
y : window.pageYOffset
}
}
// 標准模式下的IE
if( document.compatMode == "css1Compat" ){
return {
x : document.documentElement.scrollLeft,
y : document.documentElement.scrollTop
}
}
// 怪異模式下的瀏覽器
return {
x : document.body.scrollLeft,
y : document.body.scrollTop
}
}