Center a popup window on screen?

前端 未结 18 1033
一整个雨季
一整个雨季 2020-11-22 16:51

How can we center a popup window opened via javascript window.open function on the center of screen variable to the currently selected screen resolution ?

18条回答
  •  孤城傲影
    2020-11-22 17:38

    Based on Facebook's but uses a media query rather than user agent regex to calc if there is enough room (with some space) for the popup, otherwise goes full screen. Tbh popups on mobile open as new tabs anyway.

    function popupCenter(url, title, w, h) {
      const hasSpace = window.matchMedia(`(min-width: ${w + 20}px) and (min-height: ${h + 20}px)`).matches;
      const isDef = v => typeof v !== 'undefined';
      const screenX = isDef(window.screenX) ? window.screenX : window.screenLeft;
      const screenY = isDef(window.screenY) ? window.screenY : window.screenTop;
      const outerWidth = isDef(window.outerWidth) ? window.outerWidth : document.documentElement.clientWidth;
      const outerHeight = isDef(window.outerHeight) ? window.outerHeight : document.documentElement.clientHeight - 22;
      const targetWidth = hasSpace ? w : null;
      const targetHeight = hasSpace ? h : null;
      const V = screenX < 0 ? window.screen.width + screenX : screenX;
      const left = parseInt(V + (outerWidth - targetWidth) / 2, 10);
      const right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10);
      const features = [];
    
      if (targetWidth !== null) {
        features.push(`width=${targetWidth}`);
      }
    
      if (targetHeight !== null) {
        features.push(`height=${targetHeight}`);
      }
    
      features.push(`left=${left}`);
      features.push(`top=${right}`);
      features.push('scrollbars=1');
    
      const newWindow = window.open(url, title, features.join(','));
    
      if (window.focus) {
        newWindow.focus();
      }
    
      return newWindow;
    }
    

提交回复
热议问题