萬盛學電腦網

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

JavaScript 實現瀏覽器窗口最大化與自適應佈局

核心結論

現代瀏覽器安全策略禁止 JS 強制最大化窗口。window.moveTo(0,0)/resizeTo() 在大多數瀏覽器中受限,僅在 window.open 打開的無標籤頁窗口中生效。

歷史方案(僅供了解)


// 僅在 window.open 打開的窗口中生效
function maximizeWindow() {
    // 方案 1:moveTo + resizeTo
    window.moveTo(0, 0);
    window.resizeTo(screen.availWidth, screen.availHeight);
    
    // 方案 2:ActiveX (僅 IE)
    // 
    // max.Click(); // 執行 Maximize 命令
}

現代響應式佈局方案(推薦)

1. CSS Viewport 單位


.fullscreen {
    width: 100vw;
    height: 100vh;      // 視口高度
    height: 100dvh;     // 動態視口高度(移動端工具欄適配)
    max-width: 100vw;
    max-height: 100vh;
    overflow: auto;
}

2. Flex/Grid 自適應佈局


.app-layout {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}
.header { flex: 0 0 auto; }
.main { flex: 1 1 auto; overflow: auto; }
.footer { flex: 0 0 auto; }

3. 全屏 API(用戶交互觸發)


async function requestFullscreen(element = document.documentElement) {
    try {
        if (element.requestFullscreen) await element.requestFullscreen();
        else if (element.webkitRequestFullscreen) await element.webkitRequestFullscreen();
        else if (element.msRequestFullscreen) element.msRequestFullscreen();
    } catch (e) {
        console.warn('全屏請求失敗:', e);
    }
}

// 使用:必須在用戶交互事件中調用
document.getElementById('fullscreenBtn').addEventListener('click', () => {
    requestFullscreen();
});

// 退出全屏
document.exitFullscreen?.() || document.webkitExitFullscreen?.() || document.msExitFullscreen?.();

4. 檢測視口變化自適應


// 監聽視口大小變化
const resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
        const { width, height } = entry.contentRect;
        // 重新計算佈局、圖表 resize、Canvas 重繪
        console.log('視口變化:', width, height);
    }
});
resizeObserver.observe(document.body);

// 或 window.resize 事件(防抖)
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        // 重新佈局邏輯
    }, 150);
});

彈窗窗口尺寸控制


// window.open 尺寸參數(現代瀏覽器多忽略,僅作建議)
const popup = window.open(
    'page.html', 
    '_blank', 
    'width=800,height=600,left=100,top=100,resizable=yes,scrollbars=yes'
);

// 打開後嘗試調整(同源策略下可用)
popup?.addEventListener('load', () => {
    try {
        popup.resizeTo(800, 600);
        popup.moveTo((screen.width - 800) / 2, (screen.height - 600) / 2);
    } catch (e) { /* 跨域或權限拒絕 */ }
});

PWA 應用模式(類原生體驗)


/* manifest.json */
{
    "name": "我的應用",
    "short_name": "App",
    "display": "standalone",  // 隱藏瀏覽器 UI,類全屏
    "start_url": "/",
    "orientation": "portrait-primary"
}

/* 用戶可「添加到主屏幕」獲得類原生窗口體驗 */

總結建議

  1. ❌ 放棄 JS 強制最大化窗口(被瀏覽器安全策略阻攔)
  2. ✅ 採用響應式設計:100vw/100dvh + Flex/Grid
  3. ✅ 需要全屏體驗:引導用戶點擊按鈕調用 Fullscreen API
  4. ✅ PWA 模式提供最接近原生的窗口體驗
  5. ✅ 彈窗使用 window.open 但不依賴尺寸參數,內部自適應
copyright © 萬盛學電腦網 all rights reserved