想拿到頁面的可視高度、滾動距離,最惱人的莫過於各瀏覽器取值的差異。與其到處寫判斷,不如把這些瑣事全部收進一個對象裡。
復制代碼 代碼如下:
var Viewport={
top : function(){
return window.pageYOffset
|| document.documentElement && document.documentElement.scrollTop
|| document.body.scrollTop;
},
height : function(){
return window.innerHeight
|| document.documentElement && document.documentElement.clientHeight
|| document.body.clientHeight;
},
left : function(){
return window.pageXOffset
|| document.documentElement && document.documentElement.scrollLeft
|| document.body.scrollLeft;
},
width : function(){
return window.innerWidth
|| document.documentElement && document.documentElement.clientWidth
|| document.body.clientWidth;
},
right : function(){
return Viewport.left() + Viewport.width();
},
bottom : function(){
return Viewport.top() + Viewport.height();
}
};
這裡用的是最經典的短路取值:優先讀標準屬性,讀不到再退回 documentElement,最後才落到 body,一層層降級,兼容性自然穩妥。
順手實現水平垂直居中
有了這套方法,讓元素在視口中居中就變得非常輕鬆:
復制代碼 代碼如下:
style.position="absolute";
style.left=50%;
style.top=Viewport.Top()+Viewport.Height()/2+"px";