我们如何通过javascript窗口打开一个弹出窗口的中心。打开功能上的屏幕中心变量,以当前选择的屏幕分辨率?
当前回答
来源:http://www.nigraphic.com/blog/java-script/how-open-new-window-popup-center-screen
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
return targetWin;
}
其他回答
你可以使用css来做到这一点,只要给元素下面的属性被放置在弹出窗口的中心
element{
position:fixed;
left: 50%;
top: 50%;
-ms-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
我有一个问题与中心的弹出窗口在外部显示器和窗口。screenX和window。screenY分别为负值(-1920,-1200)。我已经尝试了上述所有建议的解决方案,它们在主显示器上运行良好。我想离开
左右边距为200px 顶部和底部的边缘为150像素
以下是对我有效的方法:
function createPopupWindow(url) {
var height = screen.height;
var width = screen.width;
var left, top, win;
if (width > 1050) {
width = width - 200;
} else {
width = 850;
}
if (height > 850) {
height = height - 150;
} else {
height = 700;
}
if (window.screenX < 0) {
left = (window.screenX - width) / 2;
} else {
left = (screen.width - width) / 2;
}
if (window.screenY < 0) {
top = (window.screenY + height) / 4;
} else {
top = (screen.height - height) / 4;
}
win=window.open( url,"myTarget", "width="+width+", height="+height+",left="+left+",top="+top+"menubar=no, status=no, location=no, resizable=yes, scrollbars=yes");
if (win.focus) {
win.focus();
}
}
公认的解决方案是无法工作的,除非浏览器占据全屏,
这似乎总是有效的
const popupCenterScreen = (url, title, w, h, focus) => {
const top = (screen.height - h) / 4, left = (screen.width - w) / 2;
const popup = window.open(url, title, `scrollbars=yes,width=${w},height=${h},top=${top},left=${left}`);
if (focus === true && window.focus) popup.focus();
return popup;
}
Impl:
some.function.call({data: ''})
.then(result =>
popupCenterScreen(
result.data.url,
result.data.title,
result.data.width,
result.data.height,
true));
function fnPopUpWindow(pageId) {
popupwindow("hellowWorld.php?id="+pageId, "printViewer", "500", "300");
}
function popupwindow(url, title, w, h) {
var left = Math.round((screen.width/2)-(w/2));
var top = Math.round((screen.height/2)-(h/2));
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, '
+ 'menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w
+ ', height=' + h + ', top=' + top + ', left=' + left);
}
<a href="javascript:void(0);" onclick="fnPopUpWindow('10');">Print Me</a>
注意:你必须使用数学。Round用于获得宽度和高度的精确整数。
.center { 左:50%; max-width: 350 px; 填充:15 px; text-align:中心; 位置:相对; 变换:translateX (-50%); -moz-transform: translateX (-50%); -webkit-transform: translateX (-50%); -ms-transform: translateX (-50%); -o-transform: translateX (-50%); }