要使弹出窗口在屏幕上居中,我们可以利用 JavaScript 的 window.open 函数和一些额外的计算来确定准确的位置基于当前屏幕分辨率的 x 和 y 坐标。
对于单显示器和双显示器设置,以下函数可以有效地将弹出窗口水平居中,同时考虑到它没有完全最大化的可能性:
<code class="javascript">const popupCenter = ({url, title, w, h}) => { // Adjust for dual-screen position const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX; const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY; // Calculate available screen dimensions 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 centered coordinates const left = (width - w) / 2 / systemZoom + dualScreenLeft const top = (height - h) / 2 / systemZoom + dualScreenTop // Open the new window const newWindow = window.open(url, title, ` scrollbars=yes, width=${w / systemZoom}, height=${h / systemZoom}, top=${top}, left=${left} ` ) // Bring the new window to focus if (window.focus) newWindow.focus(); }</code>
以屏幕分辨率 900x500 居中弹出窗口,标题为“XTF”:
<code class="javascript">popupCenter({url: 'http://www.xtf.dk', title: 'XTF', w: 900, h: 500});</code>
以上是如何在单显示器和双显示器设置中使弹出窗口在屏幕上居中?的详细内容。更多信息请关注PHP中文网其他相关文章!