要讓彈出視窗在螢幕上居中,我們可以利用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中文網其他相關文章!