Center a popup window on screen?

前端 未结 18 1038
一整个雨季
一整个雨季 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:40

    I had an issue with centering a popup window in the external monitor and window.screenX and window.screenY were negative values (-1920, -1200) respectively. I have tried all the above of the suggested solutions and they worked well in primary monitors. I wanted to leave

    • 200 px margin for left and right
    • 150 px margin for top and bottom

    Here is what worked for me:

     function createPopupWindow(url) {
        var height = screen.height;
        var width = screen.width;
        var left, top, win;
    
        if (width > 1050) {
            width = width - 200;
        } else {
            width = 850;
        }
    
        if (height > 850) {
            height = height - 150;
        } else {
            height = 700;
        }
    
        if (window.screenX < 0) {
            left = (window.screenX - width) / 2;
        } else {
            left = (screen.width - width) / 2;
        }
    
        if (window.screenY < 0) {
            top = (window.screenY + height) / 4;
        } else {
            top = (screen.height - height) / 4;
        }
    
        win=window.open( url,"myTarget", "width="+width+", height="+height+",left="+left+",top="+top+"menubar=no, status=no, location=no, resizable=yes, scrollbars=yes");
        if (win.focus) {
            win.focus();
        }
    }
    

提交回复
热议问题