前端仔應(yīng)該沒人不知道window.open方法吧?但是90%的人肯定都沒用過 window.open
的第三個參數(shù),你不會以為window.open就只是打開個新標(biāo)簽頁?其實它還能自定義窗口大小、位置、是否顯示菜單欄等,更爽的是還能往里面塞東西,這樣我們就有得玩了。

1?? window.open 的第三個參數(shù)怎么玩?
window.open(url, target, features)
的第三個參數(shù) features
就是用來定制新窗口樣式的!
你可以設(shè)置窗口寬高、位置、是否顯示工具欄、菜單欄、滾動條等。
常用參數(shù)如下:
參數(shù) | 作用 | 示例值 |
---|
width | 窗口寬度(像素) | 800 |
height | 窗口高度(像素) | 600 |
top | 屏幕上方距離(像素) | 100 |
left | 屏幕左側(cè)距離(像素) | 200 |
toolbar | 是否顯示工具欄 | yes/no |
menubar | 是否顯示菜單欄 | yes/no |
location | 是否顯示地址欄 | yes/no |
scrollbars | 是否允許滾動條 | yes/no |
resizable | 是否允許用戶調(diào)整窗口大小 | yes/no |
圖片預(yù)覽

<img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b3842dee8b01491ea5661debe6d9e6f9~tplv-k3u1fbpfcp-jj:240:200:0:0:q75.avis#?w=780&h=360&s=119525&e=jpg&b=a3fec8" width="200" onclick="previewImg(this.src)">
<script>
function previewImg(src) {
const width = 800, height = 600;
const left = (window.screen.width - width) / 2;
const top = (window.screen.height - height) / 2;
window.open(
src,
'_blank',
`width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes`
);
}
</script>
是不是覺得這個彈窗有點丑,別急!其實還可以定制樣式,能玩出花!
2?? 百分之99%的人都不知道,window.open 的返回值還可以用的
window.open()
返回新窗口的 window 對象。
你可以用它來動態(tài)寫入 HTML 內(nèi)容,實現(xiàn)自定義彈窗內(nèi)容(比如圖片、視頻、表單等)。
常用寫法:
const win = window.open('', '_blank', 'width=600,height=400');
win.document.write('<h1>Hello, 這是新窗口的內(nèi)容!</h1>');
win.document.write('<p>你可以塞入圖片、視頻、任何 HTML。</p>');

實用案例:圖片預(yù)覽彈窗
function previewImg(src) {
const width = 800, height = 600;
const left = (window.screen.width - width) / 2;
const top = (window.screen.height - height) / 2;
const win = window.open(
'',
'_blank',
`width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes`
);
win.document.write(`
<img src="${src}" style="max-width:100vw;max-height:100vh;display:block;margin:auto;">
`);
}
都能塞html了,那預(yù)覽video豈不是也可以?
實用案例:??視頻預(yù)覽彈窗
function previewVideo(url) {
const width = 900, height = 600;
const left = (window.screen.width - width) / 2;
const top = (window.screen.height - height) / 2;
const win = window.open(
'',
'_blank',
`width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,location=no,scrollbars=no,resizable=yes`
);
win.document.write(`
<video src="${url}" controls autoplay style="width:100vw; height:100vh; object-fit:contain; background:#000"></video>
`);
}
?? 技巧 & 注意事項
- 窗口大小建議適中,太大可能被瀏覽器攔截,太小用戶體驗不好。
- 部分參數(shù)在新標(biāo)簽頁可能無效,最好用在“彈窗式”窗口(非移動端)。
- 要結(jié)合用戶事件觸發(fā)(如點擊),否則瀏覽器可能攔截彈窗。
- 部分瀏覽器或系統(tǒng)可能限制彈窗行為,實際體驗以主流 PC 瀏覽器為準(zhǔn)。
轉(zhuǎn)自https://juejin.cn/post/7501890286550319138
該文章在 2025/5/9 10:11:56 編輯過