screen 物件| 屬性 | 說明 | 單位 |
|---|---|---|
screen.width | 螢幕寬度 | 像素 |
screen.height | 螢幕高度 | 像素 |
screen.availWidth | 可用工作區寬度(扣除任務列) | 像素 |
screen.availHeight | 可用工作區高度 | 像素 |
screen.colorDepth | 色彩深度 | bits |
screen.pixelDepth | 像素深度 | bits |
// 1. 直接彈出解析度
function showResolution() {
alert(`偵測解析度:${screen.width} x ${screen.height}`);
}
// 2. 依寬度分級判斷
function checkResolution() {
const w = screen.width;
if (w >= 1920) return 'fullhd+';
if (w >= 1440) return 'wide';
if (w >= 1024) return 'standard';
return 'legacy'; // 800, 1024 以下
}
// 3. 判斷是否為寬螢幕(比例)
function isWidescreen() {
return screen.width / screen.height >= 1.6; // 16:10 或 16:9
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>動態切換 CSS Demo</title>
<!-- 預設載入小螢幕樣式 -->
<link id="dynamic-css" rel="stylesheet" href="css/small.css">
<script>
window.addEventListener('load', function() {
const link = document.getElementById('dynamic-css');
const info = document.getElementById('info');
const width = screen.width;
if (width > 1024) {
link.href = 'css/large.css';
info.textContent = `螢幕寬度 ${width}px > 1024,已載入大螢幕樣式 (1200px, 紅底)`;
} else {
link.href = 'css/small.css';
info.textContent = `螢幕寬度 ${width}px ≤ 1024,已載入小螢幕樣式 (960px, 藍底)`;
}
});
</script>
</head>
<body>
<div id="info">載入中...</div>
</body>
</html>
* { margin: 0; padding: 0; }
div { width: 960px; height: 400px; margin: 0 auto; background: blue; color: #fff; }
* { margin: 0; padding: 0; }
div { width: 1200px; height: 400px; margin: 0 auto; background: red; color: #fff; }
function checkWallpaperFit(imgWidth, imgHeight) {
const sw = screen.width, sh = screen.height;
const imgRatio = imgWidth / imgHeight;
const scrRatio = sw / sh;
if (imgWidth === sw && imgHeight === sh) {
return { level: 'perfect', msg: '完全適合做桌面' };
}
if (imgWidth >= sw && imgHeight >= sh) {
// 圖片較大,可裁剪
return imgRatio === scrRatio
? { level: 'perfect', msg: '比例相同,直接適用' }
: { level: 'crop', msg: '需裁剪後適用' };
}
// 圖片較小
return { level: 'unfit', msg: '尺寸過小,不適合做桌布' };
}
// 使用範例:圖片 1920x1200
const result = checkWallpaperFit(1920, 1200);
console.log(result.msg); // 依使用者螢幕輸出對應提示
現代響應式設計應優先使用 CSS Media Queries,JS 偵測 screen.width 僅適用於:
/* CSS Media Query 範例 */
@media screen and (max-width: 1024px) {
.container { width: 960px; background: blue; }
}
@media screen and (min-width: 1025px) {
.container { width: 1200px; background: red; }
}
/* JS matchMedia 同步邏輯 */
if (window.matchMedia('(min-width: 1025px)').matches) {
// 大螢幕邏輯
}
| 誤區 | 正確認知 |
|---|---|
screen.width = 瀏覽器視窗寬度 | 錯誤。screen.width 是螢幕物理解析度;視窗寬度用 window.innerWidth 或 document.documentElement.clientWidth |
手機上 screen.width 等於 CSS 像素 | 錯誤。手機有 devicePixelRatio,screen.width 為裝置像素,CSS 像素 = screen.width / devicePixelRatio |
使用者縮放頁面會改變 screen.width | 錯誤。縮放只影響 window.innerWidth,screen 物件不變 |
screen.width/height 適合「硬體層級」決策(廣告載入、壁紙建議、特定裝置偵測);版型切換請改用 CSS Media Queries 或 window.matchMedia。實作時注意 devicePixelRatio 與視窗大小的差異,避免在行動裝置誤判。