萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 偵測螢幕解析度與動態切換 CSS 完整實作

應用場景

  • 依解析度載入不同廣告位或版型
  • 響應式設計前的歷史專案相容
  • 特定解析度下啟用/停用功能模組

核心 API: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
}

動態切換 CSS 完整範例

<!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>

css/small.css

* { margin: 0; padding: 0; }
div { width: 960px; height: 400px; margin: 0 auto; background: blue; color: #fff; }

css/large.css

* { 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 / matchMedia

現代響應式設計應優先使用 CSS Media Queries,JS 偵測 screen.width 僅適用於:

  • 需在 JS 邏輯中分流(如決定是否載入重型廣告 SDK)
  • 舊專案無法引入響應式 CSS 框架
  • 壁紙/截圖等需知「實際螢幕物理解析度」而非「視窗大小」的場景
/* 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 與視窗大小的差異,避免在行動裝置誤判。

copyright © 萬盛學電腦網 all rights reserved