js/jquery擷取瀏覽器視窗可視地區高度和寬度以及捲軸高度實現代碼

來源:互聯網
上載者:User

擷取瀏覽器視窗的可視地區高度和寬度,捲軸高度有需要的朋友可參考一下。
IE中,瀏覽器顯示視窗大小隻能以下擷取: 代碼如下複製代碼
複製代碼 代碼如下:
document.body.offsetWidth
document.body.offsetHeight

在聲明了DOCTYPE的瀏覽器中,可以用以下來擷取瀏覽器顯示視窗大小: 代碼如下複製代碼
複製代碼 代碼如下:
document.documentElement.clientWidth
document.documentElement.clientHeight

IE,FF,Safari皆支援該方法,opera雖支援該屬性,但是返回的是頁面尺寸;
同時,除了IE以外的所有瀏覽器都將此資訊儲存在window對象中,可以用以下擷取: 代碼如下複製代碼
複製代碼 代碼如下:
window.innerWidth
window.innerHeight

整個網頁尺寸一般獲得方法 代碼如下複製代碼
複製代碼 代碼如下:
document.body.scrollWidth
document.body.scrollHeight

螢幕解析度高度一般獲得方法 代碼如下複製代碼
複製代碼 代碼如下:
window.screen.height
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+: 
複製代碼 代碼如下:
clientWidth = width + padding
clientHeight = height + padding
offsetWidth = width + padding + border
offsetHeight = height + padding + border
IE5.0/5.5:
clientWidth = width - border
clientHeight = height - border
offsetWidth = width
offsetHeight = height

另附個人最常用的擷取整頁寬高的方法(需要jquery架構) 代碼如下複製代碼
複製代碼 代碼如下:
$(document).width() < $('body').width() ? $(document).width() : $('body').width();
$(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()); //擷取捲軸到左邊的垂直寬度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.