Javascript:在屏幕中央打开弹出窗口(Chrome)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19179403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:40:59  来源:igfitidea点击:

Javascript : open popup in the center of the screen (Chrome)

javascriptgoogle-chromepopupwindow

提问by Alberto Pellizzon

i am using this code to open a popup in the center of the screen

我正在使用此代码在屏幕中央打开一个弹出窗口

  function popupwindow(url, title, w, h) {
      wLeft = window.screenLeft ? window.screenLeft : window.screenX;
      wTop = window.screenTop ? window.screenTop : window.screenY;

      var left = wLeft + (window.innerWidth / 2) - (w / 2);
      var top = wTop + (window.innerHeight / 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 + ', screenX=' + left + ', screenY=' + top);
  }

All works fine in Firefox, IE and Safari but in Chrome the popup shows up randomly. How can i make this works also in Chrome?

在 Firefox、IE 和 Safari 中一切正常,但在 Chrome 中,弹出窗口随机显示。我怎样才能使它在 Chrome 中也能正常工作?

回答by Ibnul Hasan

I see the below code is working fine.

我看到下面的代码工作正常。

<script>
    function popupCenter(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);
    }
</script>

The Link Sample:

链接示例:

<a onclick="popupCenter('http://www.nigraphic.com', 'myPop1',450,450);" href="javascript:void(0);">CLICK TO OPEN POPUP</a>

<a onclick="popupCenter('http://www.nigraphic.com', 'myPop1',450,450);" href="javascript:void(0);">CLICK TO OPEN POPUP</a>

You can see details here

您可以在此处查看详细信息

回答by Casey

This is happening because your zoom level is not 100% in Chrome. If the zoom level is off, it changes how it gets the coordinates. In other browser, at least IE, the zoom factor does not change where the window is opened. So correct it by checking the zoom, and that will fix your problem using the given function you provided earlier while in Chrome.

发生这种情况是因为您的缩放级别在 Chrome 中不是 100%。如果缩放级别关闭,它会更改获取坐标的方式。在其他浏览器中,至少在 IE 中,缩放系数不会改变窗口打开的位置。因此,通过检查缩放来纠正它,这将使用您之前在 Chrome 中提供的给定功能来解决您的问题。

also, here is a good post about checking browser zoom levels: https://stackoverflow.com/a/5078596/2762516

另外,这里有一篇关于检查浏览器缩放级别的好文章:https: //stackoverflow.com/a/5078596/2762516