jquery獲取文檔高度和窗口高度,$(document).height()、$(window).height()
$(document).height():整個網頁的文檔高度
$(window).height():瀏覽器可視窗口的高度
$(window).scrollTop():瀏覽器可視窗口頂端距離網頁頂端的高度(垂直偏移)
$(document.body).height();//瀏覽器當前窗口文檔body的高度
$(document.body).outerHeight(true);//瀏覽器當前窗口文檔body的總高度 包括border padding margin
$(window).width(); //瀏覽器當前窗口可視區域寬度
$(document).width();//瀏覽器當前窗口文檔對象寬度
$(document.body).width();//瀏覽器當前窗口文檔body的高度
$(document.body).outerWidth(true);//瀏覽器當前窗口文檔body的總寬度 包括border padding margin
用一句話理解就是:當網頁滾動條拉到最低端時,$(document).height() == $(window).height() + $(window).scrollTop()。
當網頁高度不足瀏覽器窗口時$(document).height()返回的是$(window).height()。
不建議使用$("html").height()、$("body").height()這樣的高度。
原因:
$("body").height():body可能會有邊框,獲取的高度會比$(document).height()小;
$("html").height():在不同的瀏覽器上獲取的高度的意義會有差異,說白了就是瀏覽器不兼容。
$(window).height()值有問題,返回的不是瀏覽器窗口的高度?
原因:網頁沒有加上<!DOCTYPE>聲明。
懶人建站整理js獲取頁面高度和窗口高度
實際應用:設置內容區域合適的高度
| 代碼如下 | 復制代碼 |
| //設置內容區域合適高度 |
|
注:winH+4 因為IE8下只有4像素偏差
例
| 代碼如下 | 復制代碼 |
| // 獲取頁面的高度、寬度 function getPageSize() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else { if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } } var windowWidth, windowHeight;//www.111cn.net if (self.innerHeight) { // all except Explorer if (document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else { if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } } } // for small pages with total height less then height of the viewport if (yScroll < windowHeight) { pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if (xScroll < windowWidth) { pageWidth = xScroll; } else { pageWidth = windowWidth; } arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight); return arrayPageSize; } // 滾動條 document.body.scrollTop; $(document).scrollTop(); |
|
