在瀏覽器中開啟新視窗有許多種寫法,各有不同的控制能力與適用場合。本文整理了從最簡單到進階的多種 JavaScript 開窗方式。
最直接的方式是改變 location,但這只會在當前頁開啟:
window.location="aaa.aspx"
若要在新頁面開啟,可用表單的 target:
form.target="_blank";
form.action="aaa.aspx";
form.submit();
想在 iframe 中的頁面讓父窗口刷新,可用:
window.top.location=url
window.open 能控制視窗大小、位置與內容,功能最豐富,缺點是容易被瀏覽器攔截。以下示範全屏開啟:
<SCRIPT>
function ow(owurl){
var tmp=window.open("about:blank","","fullscreen=1")
tmp.moveTo(0,0);
tmp.resizeTo(screen.width+20,screen.height);
tmp.focus();
tmp.location=owurl;
}
</SCRIPT>
固定視窗尺寸:
<button onclick="window.open('/red/','','width=800,height=300')">open1</button>
開啟後再動態調整大小:
<button onclick="var newwin=window.open('/red/');newwin.moveTo(50,50);newwin.resizeTo(800,300)">open2</button>
此外還有 showModelessDialog 網頁對話框、子視窗開啟後關閉父視窗等變化:
<script>
window.open('https://www.aspxhome.com/','','width=790,height=590');
window.opener=null;
window.close();
</script>
可依據「是否要控制尺寸位置」「是否要避免被攔截」等需求,挑選最合適的開窗方式。