DIV CSS 佈局教程網

JavaScript 入門教學(5):Screen 螢幕物件與可用區域判斷
編輯:JavaScript基礎知識     

Screen 物件做什麼用?

Screen 物件反映的是使用者「實體螢幕」的設定,而非瀏覽器視窗的大小。這個區別很關鍵:window.innerWidth 告訴你可用的視窗空間,screen.width 告訴你螢幕本身的解析度。當你想針對大螢幕與小螢幕設計不同的版面策略,或需要計算視窗能開到多大時,就會用到它。

核心屬性

width 與 height

分別回傳螢幕的寬與高,單位為像素。這是整个螢幕的實際尺寸,包含被工作列等介面元素遮住的區域。

availWidth 與 availHeight

回傳「可用」的寬與高,也就是從實體尺寸中扣除作業系統常駐介面所佔的空間。最典型的例子就是 Windows 工作列:若工作列固定在畫面下方,availHeight 就會比 height 少幾十個像素。因此當你想把視窗最大化到「剛好填滿不被遮住的區域」時,應該用 avail 系列而非 width/height。

colorDepth 與 pixelDepth

回傳目前色彩設定的位元深度,常見值與對應意義如下:

  • 1:黑白
  • 8:256 色
  • 16:增強色
  • 24 或 32:真彩色

pixelDepth 表達的是每個像素的色彩解析度,若系統未啟用調色盤,colorDepth 的數值會直接沿用 pixelDepth。

英文原始文件對照

以下是 Navigator 系列瀏覽器文件中對 Screen 物件的原文定義,可作為理解上述屬性的補充:

  • availHeight: minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
  • availWidth: Specifies the width of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
  • colorDepth: The bit depth of the color palette, if one is in use; otherwise, the value is derived from screen.pixelDepth.
  • height: Display screen height.
  • pixelDepth: Display screen color resolution (bits per pixel).
  • width: Display screen width.

實務上的提醒

Screen 物件的所有屬性都是唯讀的,你無法透過腳本更改使用者的解析度。此外,行動裝置與高 DPI 螢幕的出現,讓單純依賴 screen.width 做版面判斷變得不可靠——裝置像素比(devicePixelRatio)會讓回傳值與實際物理像素不一致。因此在現代開發中,響應式設計與 CSS media query 才是處理多尺寸的正規手段,Screen 物件則適合用於收集使用者環境資訊或調整彈出視窗的初始大小。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved