現代瀏覽器安全策略禁止 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 命令
}
.fullscreen {
width: 100vw;
height: 100vh; // 視口高度
height: 100dvh; // 動態視口高度(移動端工具欄適配)
max-width: 100vw;
max-height: 100vh;
overflow: auto;
}
.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; }
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?.();
// 監聽視口大小變化
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) { /* 跨域或權限拒絕 */ }
});
/* manifest.json */
{
"name": "我的應用",
"short_name": "App",
"display": "standalone", // 隱藏瀏覽器 UI,類全屏
"start_url": "/",
"orientation": "portrait-primary"
}
/* 用戶可「添加到主屏幕」獲得類原生窗口體驗 */
100vw/100dvh + Flex/Gridwindow.open 但不依賴尺寸參數,內部自適應