在屏幕上居中显示弹出窗口?

2022-08-29 23:53:54

我们如何在屏幕变量的中心上将通过javascript函数打开的弹出窗口居中到当前选定的屏幕分辨率?window.open


答案 1

单/双显示器功能(归功于 http://www.xtf.dk - 谢谢!

更新:由于@Frost,它现在还可以在未达到屏幕宽度和高度的窗口上工作!

如果您使用的是双显示器,则窗口将水平居中,但不会垂直...使用此函数来说明这一点。

const popupCenter = ({url, title, w, h}) => {
    // Fixes dual-screen position                             Most browsers      Firefox
    const dualScreenLeft = window.screenLeft !==  undefined ? window.screenLeft : window.screenX;
    const dualScreenTop = window.screenTop !==  undefined   ? window.screenTop  : window.screenY;

    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    const systemZoom = width / window.screen.availWidth;
    const left = (width - w) / 2 / systemZoom + dualScreenLeft
    const top = (height - h) / 2 / systemZoom + dualScreenTop
    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 (我只想链接到这个页面,但以防万一这个网站关闭了代码在这里 SO,干杯!


答案 2

试试这个:

function popupwindow(url, title, w, h) {
  var left = (screen.width/2)-(w/2);
  var top = (screen.height/2)-(h/2);
  return window.open(url, 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);
}