简体   繁体   中英

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

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?

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>

You can see details here

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM