JavaScript 实现居中弹窗:open() 与 showModalDialog() 方法详解

作者:代码拾荒

时间:2026-10-28

浏览:316

本文介绍了在 JavaScript 项目中实现居中弹窗的两种常用方法:window.open 和 window.showModalDialog。通过计算屏幕宽高与窗口尺寸的差值,动态设置 top 和 left 属性,确保弹窗在页面中居中显示。文章提供了完整的函数代码示例,涵盖参数配置、浏览器兼容性处理及样式控制,适用于需要模态或非模态弹窗交互的开发场景。

文章目录

使用 window.open 实现居中弹窗

该方法通用,项目开发中频繁使用:


代码如下:

 
//w:宽,h:高,url:地址,tag:标记
function showWin(w, h, url, tag) {
var t = (screen.height - h) / 2; //离顶部距离
var l = (screen.width - w) / 2; //离左边距离
window.open(url, tag, "width=" + w + ",height=" + h + ",top=" + t + ",left=" + l + ",location=0");
} 
使用 showModalDialog 及兼容性处理//路径地址,window对象,宽,高
function open_Dialog(url, win,Width, Height) {
var return_Value;
var iTop2 = (window.screen.availHeight - 20 - Height) / 2;
var iLeft2 = (window.screen.availWidth - 10 - Width) / 2;
var height2 = Height - 50;
if (document.all && window.print) {
return_Value = window.showModalDialog(url, win, "dialogLeft:" + iLeft2 + "px;dialogTop:" + iTop2 + "px;dialogWidth:",
Width + "px;dialogHeight:" + Height + "px;center:yes;status:no;scroll:no;help:no;");
} 
else {
window.open(url, win, "top=" + iTop2 + ",left=" + iLeft2 + ",width=" + Width + "px,height=" + height2 +
"px,resizable=0,scrollbars=0,location=0");
} 
} 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章