1. 程式人生 > >JS如何獲取屏幕、瀏覽器及網頁高度寬度?

JS如何獲取屏幕、瀏覽器及網頁高度寬度?

定位 idt 隨筆 highlight class 範圍 eight 工作 任務

目的

在瀏覽器中,用JS獲取高度和寬度都各有3種,分別包括屏幕,瀏覽器和網頁的。用來解決各種計算定位問題!以至於我各種記不住,寫個隨筆方便查詢。

屏幕寬高

說明:顧名思義,屏幕寬高是指顯示器的分辨率。系統分辨率可以改變這個寬高。

獲取方法:

console.log(‘寬度:‘, window.screen.width)
console.log(‘高度:‘, window.screen.height)

瀏覽器可用工作區的寬高

說明:瀏覽器寬高是指瀏覽器窗口最大化時的寬高,普通的最大化後,一般就是去掉系統任務欄高度,而寬度和屏幕寬是一樣的。這個寬高在任務欄占用空間變化時會變化。

  獲取方法:

console.log(‘寬度:‘, window.screen.availWidth)
console.log(‘高度:‘, window.screen.availHeight)

網頁寬高

說明:網頁寬高,是指頁面所占的寬高,瀏覽器除了頁面內容以外的部分,不計算在內。標簽欄,地址欄,書簽欄,控制臺等全不計算在寬高的範圍裏面,只有網頁內容區域才是

獲取方法:

console.log(‘寬度:‘, window.innerWidth)
console.log(‘高度:‘, window.innerHeight)

其他(獲取瀏覽器和屏幕各種高度寬度)

js原生方法:

document.body.clientWidth;        //網頁可見區域寬(body)

document.body.clientHeight;       //網頁可見區域高(body)

document.body.offsetWidth;        //網頁可見區域寬(body),包括border、margin等

document.body.offsetHeight;       //網頁可見區域寬(body),包括border、margin等

document.body.scrollWidth;        //網頁正文全文寬,包括有滾動條時的未見區域

document.body.scrollHeight;       //網頁正文全文高,包括有滾動條時的未見區域

document.body.scrollTop;          //網頁被卷去的Top(滾動條)

document.body.scrollLeft;         //網頁被卷去的Left(滾動條)

window.screenTop;                 //瀏覽器距離Top

window.screenLeft;                //瀏覽器距離Left

  jQuery方法:

$(window).height();                    //瀏覽器當前窗口可視區域高度

$(document).height();                  //瀏覽器當前窗口文檔的高度

$(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

  

JS如何獲取屏幕、瀏覽器及網頁高度寬度?