JavaScript を使用して、異なるサイズのウィンドウのポップアップ位置を制御したいと考えています。
どうすればいいですか?
標準的なポップアップについて話していると思いますがwindow.open
、そうでない場合は教えてください。
あなたがしなければならないことはとても簡単です。まず、screen
オブジェクトを使用してクライアントの画面サイズを調べます。
var screenWidth = screen.width;
var screenHeight = screen.height;
画面のサイズがわかったので、たとえば、800x600 の寸法の中央に配置されたポップアップの左上隅を計算するために使用できます。
var top = screenWidth/2 - 300;
var left = screenHeight/2 - 400;
これで、準備が整いました。
var myCenteredWindow = window.open(myURL,'myFancyPopup','width=800,height=600,scrollbars=no,top=' + top + ',left=' + left + '');
これは簡単に 1 行に書き込めることに注意してください (何が起こっているかがわかったとき)。
var myCenteredWindow = window.open(myURL,'myFancyPopup','width=800,height=600,scrollbars=no,top=' + screen.width/2 - 300 + ',left=' + screen.height/2 - 400 + '');
ポップアップ ダイアログ ウィンドウをさまざまなウィンドウ サイズで制御するには、ウィンドウの幅とダイアログの幅を使用して、ダイアログの位置を計算します。たとえば、次のようにします。ウィンドウの幅、これを試してください:
var windowWidth = $(window).width(); //get the windows width;
var dialogWidth = $("#popup-dialog").width(); // get the dialog width;
var pLeft = (windowWidth - dialogWidth) / 2;
$("#dialog").css("left", pLeft);