我们如何通过javascript窗口打开一个弹出窗口的中心。打开功能上的屏幕中心变量,以当前选择的屏幕分辨率?


当前回答

公认的解决方案是无法工作的,除非浏览器占据全屏,

这似乎总是有效的

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

其他回答

它在Firefox中运行得非常好。 只需将顶部变量更改为任何其他名称,然后再试一次

        var w = 200;
        var h = 200;
        var left = Number((screen.width/2)-(w/2));
        var tops = Number((screen.height/2)-(h/2));

window.open("templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);

我的ES6 JavaScript版本。 工作良好的铬和铬双屏幕设置。

function openCenteredWindow({url, width, height}) {
    const pos = {
        x: (screen.width / 2) - (width / 2),
        y: (screen.height/2) - (height / 2)
    };

    const features = `width=${width} height=${height} left=${pos.x} top=${pos.y}`;

    return window.open(url, '_blank', features);
}

例子

openCenteredWindow({
    url: 'https://stackoverflow.com/', 
    width: 500, 
    height: 600
}).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 popupWindow(url, windowName, win, w, h) {
    const y = win.top.outerHeight / 2 + win.top.screenY - ( h / 2);
    const x = win.top.outerWidth / 2 + win.top.screenX - ( w / 2);
    return win.open(url, windowName, `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${y}, left=${x}`);
}

实现:

popupWindow('google.com', 'test', window, 200, 100);

.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%); }