具有不同窗口大小的jQuery弹出位置

jQuery Popup position with different window size

本文关键字:jQuery 出位 位置 窗口大小      更新时间:2023-09-26

我想使用 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 + '');

请注意,这可以很容易地写成一行(当你明白发生了什么时):

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);