如何将弹出窗口精确定位在屏幕中央
将使用 JavaScript 的 window.open 函数创建的弹出窗口居中屏幕对于最佳用户体验至关重要。确切的坐标取决于屏幕分辨率,因此需要动态解决方案。
解决方案:利用单/双显示器功能
一个强大的解决方案,可同时容纳单显示器和双显示器双显示器设置如下:
const popupCenter = ({ url, title, w, h }) => {
// Determine the positions based on screen resolution
const dualScreenLeft = window.screenLeft || window.screenX;
const dualScreenTop = window.screenTop || window.screenY;
const width = window.innerWidth || document.documentElement.clientWidth || screen.width;
const height = window.innerHeight || document.documentElement.clientHeight || screen.height;
// Adjust for system zoom
const systemZoom = width / window.screen.availWidth;
// Calculate the centered coordinates
const left = (width - w) / 2 / systemZoom dualScreenLeft;
const top = (height - h) / 2 / systemZoom dualScreenTop;
// Open the popup window with the calculated dimensions and positioning
const newWindow = window.open(url, title,
`
scrollbars=yes,
width=${w / systemZoom},
height=${h / systemZoom},
top=${top},
left=${left}
`
);
if (window.focus) newWindow.focus();
};
用法示例:
popupCenter({ url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500 });
来源和来源:
这个解决方案,最初来自http://www.xtf.dk/2011/08/center-new-popup-window-even -on.html,有效处理各种屏幕配置的弹出窗口居中。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3