前端仔应该没人不知道window.open方法吧?但是90%的人肯定都没用过 window.open
的第三个参数,你不会以为window.open就只是打开个新标签页?其实它还能自定义窗口大小、位置、是否显示菜单栏等,更爽的是还能往里面塞东西,这样我们就有得玩了。

1️⃣ window.open 的第三个参数怎么玩?
window.open(url, target, features)
的第三个参数 features
就是用来定制新窗口样式的!
你可以设置窗口宽高、位置、是否显示工具栏、菜单栏、滚动条等。
常用参数如下:
参数 | 作用 | 示例值 |
---|
width | 窗口宽度(像素) | 800 |
height | 窗口高度(像素) | 600 |
top | 屏幕上方距离(像素) | 100 |
left | 屏幕左侧距离(像素) | 200 |
toolbar | 是否显示工具栏 | yes/no |
menubar | 是否显示菜单栏 | yes/no |
location | 是否显示地址栏 | yes/no |
scrollbars | 是否允许滚动条 | yes/no |
resizable | 是否允许用户调整窗口大小 | yes/no |
图片预览

<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 对象。
你可以用它来动态写入 HTML 内容,实现自定义弹窗内容(比如图片、视频、表单等)。
常用写法:
const win = window.open('', '_blank', 'width=600,height=400');
win.document.write('<h1>Hello, 这是新窗口的内容!</h1>');
win.document.write('<p>你可以塞入图片、视频、任何 HTML。</p>');

实用案例:图片预览弹窗
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了,那预览video岂不是也可以?
实用案例:🎬视频预览弹窗
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>
`);
}
🎯 技巧 & 注意事项
- 窗口大小建议适中,太大可能被浏览器拦截,太小用户体验不好。
- 部分参数在新标签页可能无效,最好用在“弹窗式”窗口(非移动端)。
- 要结合用户事件触发(如点击),否则浏览器可能拦截弹窗。
- 部分浏览器或系统可能限制弹窗行为,实际体验以主流 PC 浏览器为准。
转自https://juejin.cn/post/7501890286550319138
该文章在 2025/5/9 10:11:56 编辑过