JavaScript の関数を使用して開かれたポップアップ ウィンドウを画面の中央に配置するにはどうすればよいですかwindow.open
(正確なx座標とy座標は現在の画面解像度によって異なります)?
ベストアンサー1
シングル/デュアルモニター機能(クレジット:翻訳元- ありがとう!)
更新: @Frost のおかげで、画面の幅と高さが最大になっていないウィンドウでも機能するようになりました。
デュアル モニターを使用している場合、ウィンドウは水平方向には中央に配置されますが、垂直方向には中央に配置されません。これに対処するには、この機能を使用します。
const popupCenter = ({url, title, w, h}) => {
// Fixes dual-screen position Most browsers Firefox
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
const systemZoom = width / window.screen.availWidth;
const left = (width - w) / 2 / systemZoom + dualScreenLeft
const top = (height - h) / 2 / systemZoom + dualScreenTop
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(このページにリンクしたかったのですが、この Web サイトがダウンした場合に備えて、コードは SO にあります。)