「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > ポップアップ ウィンドウをブラウザの中央に配置するにはどうすればよいですか?

ポップアップ ウィンドウをブラウザの中央に配置するにはどうすればよいですか?

2024 年 11 月 22 日に公開
ブラウズ:925

How to Center a Popup Window in the Browser?

ポップアップ ウィンドウを画面の中央に正確に配置する方法

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