這是一個經典的 JS 特效:點擊頁面上的指定連結,瀏覽器視窗會自動縮小至螢幕的一定比例,並置中顯示,隨後在該視窗中載入連結目標內容。雖然現代瀏覽器對 window.resizeTo 與 window.moveTo 的限制較多,但理解其原理仍有助於掌握視窗操作技巧。
window.resizeTo() 調整大小window.moveTo() 移至螢幕中心<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>視窗縮放置中示範</title>
</head>
<body style="text-align:center; padding-top:50px;">
<h2>點擊連結觀察視窗變化</h2>
<a href="#" onclick="resizeAndCenter(50, 50); return false;">點我縮放至 50% 並置中</a>
<script>
function resizeAndCenter(widthPercent, heightPercent) {
var w = screen.availWidth * widthPercent / 100;
var h = screen.availHeight * heightPercent / 100;
window.resizeTo(w, h);
window.moveTo(
Math.ceil((screen.availWidth - w) / 2),
Math.ceil((screen.availHeight - h) / 2)
);
}
</script>
</body>
</html>
window.open() 開啟的彈出視窗有效。window.open(url, '_blank', 'width=...,height=...,left=...,top=...')。