Center a popup window on screen?

前端 未结 18 1037
一整个雨季
一整个雨季 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条回答
  •  旧时难觅i
    2020-11-22 17:19

    My version with ES6 JavaScript.
    Works well on Chrome and Chromium with dual screen setup.

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

    Example

    openCenteredWindow({
        url: 'https://stackoverflow.com/', 
        width: 500, 
        height: 600
    }).focus();
    

提交回复
热议问题