獲取瀏覽器窗口的可視區域高度和寬度,滾動條高度有需要的朋友可參考一下。
IE中,瀏覽器顯示窗口大小只能以下獲取: 代碼如下復制代碼
1 document.body.offsetWidth 2 document.body.offsetHeight
在聲明了DOCTYPE的瀏覽器中,可以用以下來獲取瀏覽器顯示窗口大小: 代碼如下復制代碼
1 document.documentElement.clientWidth 2 document.documentElement.clientHeight
IE,FF,Safari皆支持該方法,opera雖支持該屬性,但是返回的是頁面尺寸;
同時,除了IE以外的所有瀏覽器都將此信息保存在window對象中,可以用以下獲取: 代碼如下復制代碼
1 window.innerWidth 2 window.innerHeight
整個網頁尺寸一般獲得方法 代碼如下復制代碼
1 document.body.scrollWidth 2 document.body.scrollHeight
屏幕分辨率高度一般獲得方法 代碼如下復制代碼
1 window.screen.height 2 window.screen.width
總結一下實例
function getViewSizeWithoutScrollbar(){//不包含滾動條 return { width : document.documentElement.clientWidth, height: document.documentElement.clientHeight } } function getViewSizeWithScrollbar(){//包含滾動條 if(window.innerWidth){ return { width : window.innerWidth, height: window.innerHeight } }else if(document.documentElement.offsetWidth == document.documentElement.clientWidth){ return { width : document.documentElement.offsetWidth, height: document.documentElement.offsetHeight } }else{ return { width : document.documentElement.clientWidth + getScrollWith(), height: document.documentElement.clientHeight + getScrollWith() } } }
IE,FireFox 差異如下:
IE6.0、FF1.06+:
1 clientWidth = width + padding 2 clientHeight = height + padding 3 offsetWidth = width + padding + border 4 offsetHeight = height + padding + border 5 IE5.0/5.5: 6 clientWidth = width - border 7 clientHeight = height - border 8 offsetWidth = width 9 offsetHeight = height
另附個人最常用的獲取整頁寬高的方法(需要jquery框架) 代碼如下復制代碼
1 $(document).width() < $('body').width() ? $(document).width() : $('body').width(); 2 $(document).height() < $('body').height() ? $(document).height() : $('body').height();
alert($(window).height()); //瀏覽器時下窗口可視區域高度
alert($(document).height()); //瀏覽器時下窗口文檔的高度
alert($(document.body).height());//瀏覽器時下窗口文檔body的高度
alert($(document.body).outerHeight(true));//瀏覽器時下窗口文檔body的總高度 包括border padding margin
alert($(window).width()); //瀏覽器時下窗口可視區域寬度
alert($(document).width());//瀏覽器時下窗口文檔對於象寬度
alert($(document.body).width());//瀏覽器時下窗口文檔body的高度
alert($(document.body).outerWidth(true));//瀏覽器時下窗口文檔body的總寬度 包括border padding margin
alert($(document).scrollTop()); //獲取滾動條到頂部的垂直高度
alert($(document).scrollLeft()); //獲取滾動條到左邊的垂直寬度
來源:http://www.jb51.net/article/32679.htm