จัดกึ่งกลางหน้าต่างป๊อปอัปบนหน้าจอหรือไม่


280

เราจะจัดกึ่งกลางหน้าต่างป็อปอัพที่เปิดผ่านwindow.openฟังก์ชั่นจาวาสคริปต์ที่กึ่งกลางหน้าจอตัวแปรไปที่ความละเอียดหน้าจอที่เลือกในปัจจุบันได้อย่างไร?

คำตอบ:


458

ฟังก์ชั่นการติดตามผลเดี่ยว / คู่ (เครดิตถึงhttp://www.xtf.dk - ขอขอบคุณ!)

UPDATE: นอกจากนี้ยังสามารถใช้งานบนหน้าต่างที่ไม่ได้ขยายให้กว้างและสูงของหน้าจอได้ในตอนนี้ด้วย @Frost!

หากคุณอยู่บนจอภาพสองจอหน้าต่างจะอยู่ตรงกลางในแนวนอน แต่ไม่ใช่ในแนวตั้ง ... ใช้ฟังก์ชั่นนี้ในการทำสิ่งนั้น

const popupCenter = ({url, title, w, h}) => {
    // Fixes dual-screen position                             Most browsers      Firefox
    const dualScreenLeft = window.screenLeft !==  undefined ? window.screenLeft : window.screenX;
    const dualScreenTop = window.screenTop !==  undefined   ? window.screenTop  : window.screenY;

    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    const systemZoom = width / window.screen.availWidth;
    const left = (width - w) / 2 / systemZoom + dualScreenLeft
    const top = (height - h) / 2 / systemZoom + dualScreenTop
    const newWindow = window.open(url, title, 
      `
      scrollbars=yes,
      width=${w / systemZoom}, 
      height=${h / systemZoom}, 
      top=${top}, 
      left=${left}
      `
    )

    if (window.focus) newWindow.focus();
}

ตัวอย่างการใช้งาน:

popupCenter({url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500});  

เครดิตไปที่: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html (ฉันต้องการลิงก์ไปยังหน้านี้ แต่ในกรณีที่เว็บไซต์นี้ลง รหัสอยู่ที่นี่ดังนั้น, ไชโย!)


7
หลังจากเล่นไปเรื่อย ๆ มันก็ใช้งานไม่ได้อย่างที่คิด คำตอบที่ยกเว้นง่ายกว่าทำงานได้ดีกว่ามาก ใช้งานได้ก็ต่อเมื่อหน้าการเรียกใช้นั้นขยายใหญ่สุด
บาร์ต

8
ขอบคุณสำหรับเครดิตที่ผมได้ทำตัวอย่างของฉันทำงานบน Windows ลดลงขณะนี้: xtf.dk/2011/08/center-new-popup-window-even-on.html
ฟรอสต์

10
ใช้ตัวแปรทั่วโลก (กว้าง / สูง) ouch!
Ruben Stolk

13
คำถามเดิมที่โพสต์ในปี 2010, คำตอบเดิมที่โพสต์ในปี 2010 ความคิดเห็นของฉันเกี่ยวกับการแก้ปัญหาดั้งเดิมเกี่ยวกับการไม่ทำงานกับจอภาพสองจอที่โพสต์ในปี 2013 คำตอบของฉันสำหรับจอภาพสองจอ โซลูชันสามจอภาพในปี 2558 ในอัตรานี้เราจะได้คำตอบสำหรับ 5 จอภาพในปี 2020, 6 จอภาพใน 2025, 7 จอภาพใน 2030 ... ขอให้วงจรนี้ดำเนินต่อไป!
Tony M

2
@TonyM ฉันได้อัปเดตคำตอบแล้ว ใช่วงจรต้องดำเนินต่อไป!
Zo มี

329

ลองแบบนี้:

function popupwindow(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);
} 

17
ฟังก์ชั่นนี้ใช้ไม่ได้กับการตั้งค่าจอภาพสองจอ ฉันโพสต์โซลูชันเดี่ยวและจอภาพสองจอด้านล่าง
Tony M

1
ฉันต้องการยืนยันสิ่งนี้: var left = (screen.width / 2) - (w / 2); var top = (screen.height / 2) - (h / 2); ใช่ไหมมันจะกลับไปทางซ้าย = 0 และด้านบน = 0 ??? สมมติว่า w เท่ากับ screen.width และ h เท่ากับ screen.height ... ฉันถูกหรือผิดที่นี่
mutican

1
@mutanic w / h อ้างอิงถึงขนาดของป๊อปอัปไม่ใช่ที่หน้าจอ
Mahn

2
ไม่ได้มุ่งเน้นที่จอภาพที่สองของฉัน (ซึ่งขึ้นจากหน้าจอหลัก) คำตอบสำหรับหน้าจอคู่ล้มเหลวเช่นกัน
vsync

2
สิ่งนี้จะไม่ทำงานหากคุณต้องการหน้าต่างกลางตรงกลางของเบราว์เซอร์แทนที่จะอยู่ตรงกลางของหน้าจอ (ตัวอย่างเช่นผู้ใช้ปรับขนาดเบราว์เซอร์เป็นครึ่งขนาด) หากต้องการจัดกึ่งกลางภายในเบราว์เซอร์ให้แทนที่ screen.width & screen.height ด้วย window.innerWidth & window.innerHeight
Jonathon Blok

71

เนื่องจากความซับซ้อนในการกำหนดจุดกึ่งกลางของหน้าจอปัจจุบันในการตั้งค่าหลายจอภาพตัวเลือกที่ง่ายกว่าคือการวางป็อปอัพที่กึ่งกลางหน้าต่างหลัก เพียงผ่านหน้าต่างหลักเป็นพารามิเตอร์อื่น:

function popupWindow(url, title, win, w, h) {
    const y = win.top.outerHeight / 2 + win.top.screenY - ( h / 2);
    const x = win.top.outerWidth / 2 + win.top.screenX - ( w / 2);
    return win.open(url, title, `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${y}, left=${x}`);
}

การดำเนินงาน:

popupWindow('google.com', 'test', window, 200, 100);

นี่เป็นเทคนิคที่ Facebook ใช้สำหรับป๊อปอัปในปุ่มแชร์
Tim Tisdall

3
มันทำงานได้อย่างสมบูรณ์แบบสำหรับฉันบนหน้าจอคู่ แม้ว่าจะย้ายหรือปรับขนาดหน้าต่างมันก็บอกว่าอยู่ตรงกลางของหน้าต่างที่เปิดจาก นี่ควรเป็นคำตอบที่ยอมรับได้ ขอบคุณ
Oli B

2
ฉันเห็นด้วยกับ @OliB - มันทำงานได้อย่างสมบูรณ์และแก้ไขปัญหาการพัฒนาล่าสุดที่เรามี! ควรเป็นคำตอบที่ได้รับการยอมรับสำหรับปี 2562
MrLewk

ทำให้การปรับเปลี่ยนเพื่อขยายขีดความสามารถของฟังก์ชั่นนี้ได้ที่นี่ มันมีตัวเลือกในการตั้งค่าความกว้างและความสูงเป็นร้อยละหรืออัตราส่วน นอกจากนี้คุณยังสามารถเปลี่ยนตัวเลือกด้วยวัตถุ (จัดการได้ง่ายกว่าสตริง)
SwiftNinjaPro


15

หากคุณต้องการจัดกึ่งกลางมันไว้ในเฟรมที่คุณอยู่ฉันจะแนะนำฟังก์ชั่นนี้:

function popupwindow(url, title, w, h) {
    var y = window.outerHeight / 2 + window.screenY - ( h / 2)
    var x = window.outerWidth / 2 + window.screenX - ( w / 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=' + y + ', left=' + x);
} 

คล้ายกับคำตอบของ Crazy Tim แต่ไม่ได้ใช้ window.top วิธีนี้จะทำงานแม้ว่าจะฝังหน้าต่างใน iframe จากโดเมนอื่น


13

มันทำงานได้ดีมากใน Firefox
เพียงเปลี่ยนตัวแปรด้านบนเป็นชื่ออื่นแล้วลองอีกครั้ง

        var w = 200;
        var h = 200;
        var left = Number((screen.width/2)-(w/2));
        var tops = Number((screen.height/2)-(h/2));

window.open("templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);

6
Number(...)มันไม่จำเป็นทั้งหมดที่จะทำ
gustavohenke

6

คำแนะนำของฉันคือการใช้ตำแหน่งด้านบน 33% หรือ 25% จากพื้นที่ที่เหลืออยู่
และไม่ได้ 50% เป็นตัวอย่างอื่น ๆ โพสต์ที่นี่
ส่วนใหญ่เป็นเพราะหัวหน้าต่าง ,
ซึ่งดูดีขึ้นและสะดวกสบายมากขึ้นให้กับผู้ใช้

รหัสสมบูรณ์:

    <script language="javascript" type="text/javascript">
        function OpenPopupCenter(pageURL, title, w, h) {
            var left = (screen.width - w) / 2;
            var top = (screen.height - h) / 4;  // for 25% - devide by 4  |  for 33% - devide by 3
            var targetWin = window.open(pageURL, 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>
</head>
<body>
    <button onclick="OpenPopupCenter('http://www.google.com', 'TEST!?', 800, 600);">click on me</button>
</body>
</html>



ลองดูบรรทัดนี้:
var top = (screen.height - h) / 4; // สำหรับ 25% - แบ่งตาม 4 | สำหรับ 33% - แบ่งตาม 3


6

Facebook ใช้อัลกอริทึมต่อไปนี้เพื่อจัดตำแหน่งหน้าต่างป๊อปอัพการเข้าสู่ระบบ:

function PopupCenter(url, title, w, h) {
  var userAgent = navigator.userAgent,
      mobile = function() {
        return /\b(iPhone|iP[ao]d)/.test(userAgent) ||
          /\b(iP[ao]d)/.test(userAgent) ||
          /Android/i.test(userAgent) ||
          /Mobile/i.test(userAgent);
      },
      screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
      screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
      outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth,
      outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : document.documentElement.clientHeight - 22,
      targetWidth = mobile() ? null : w,
      targetHeight = mobile() ? null : h,
      V = screenX < 0 ? window.screen.width + screenX : screenX,
      left = parseInt(V + (outerWidth - targetWidth) / 2, 10),
      right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10),
      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');

  var newWindow = window.open(url, title, features.join(','));

  if (window.focus) {
    newWindow.focus();
  }

  return newWindow;
}

4

คุณสามารถใช้ css เพื่อทำเพียงให้คุณสมบัติต่อไปนี้กับองค์ประกอบที่จะวางไว้ที่กึ่งกลางของป๊อปอัพ

element{

position:fixed;
left: 50%;
top: 50%;
-ms-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
 transform: translate(-50%,-50%);

}

3

นี่เป็นเวอร์ชั่นสำรองของโซลูชันดังกล่าว ...

function openPopupCenter(url, title, w, h) {
  // Fixes dual-screen position
  // Most browsers use window.screenLeft
  // Firefox uses screen.left
  var dualScreenLeft = getFirstNumber(window.screenLeft, screen.left),
    dualScreenTop = getFirstNumber(window.screenTop, screen.top),
    width = getFirstNumber(window.innerWidth, document.documentElement.clientWidth, screen.width),
    height = getFirstNumber(window.innerHeight, document.documentElement.clientHeight, screen.height),
    left = ((width / 2) - (w / 2)) + dualScreenLeft,
    top = ((height / 2) - (h / 2)) + dualScreenTop,
    newWindow = window.open(url, title, getSpecs());

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
  }

  return newWindow;

  function getSpecs() {
    return 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left;
  }

  function getFirstNumber() {
    for(var i = 0, len = arguments.length; i < len; i++) {
      var value = arguments[i];

      if (typeof value === 'number') {
        return value;
      }
    }
  }
}

3

รุ่นของฉันกับ ES6 JavaScript
ทำงานได้ดีบน Chrome และ Chromium ด้วยการตั้งค่าหน้าจอคู่

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

ตัวอย่าง

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

2

(สิ่งนี้ถูกโพสต์ในปี 2020)

ส่วนขยายของคำตอบของ CrazyTim

คุณยังสามารถตั้งค่าความกว้างเป็นเปอร์เซ็นต์ (หรืออัตราส่วน) สำหรับขนาดแบบไดนามิก ขนาดที่แน่นอนยังคงได้รับการยอมรับ

function popupWindow(url, title, w='75%', h='16:9', opts){
    // sort options
    let options = [];
    if(typeof opts === 'object'){
        Object.keys(opts).forEach(function(value, key){
            if(value === true){value = 'yes';}else if(value === false){value = 'no';}
            options.push(`${key}=${value}`);
        });
        if(options.length){options = ','+options.join(',');}
        else{options = '';}
    }else if(Array.isArray(opts)){
        options = ','+opts.join(',');
    }else if(typeof opts === 'string'){
        options = ','+opts;
    }else{options = '';}

    // add most vars to local object (to shorten names)
    let size = {w: w, h: h};
    let win = {w: {i: window.top.innerWidth, o: window.top.outerWidth}, h: {i: window.top.innerHeight, o: window.top.outerHeight}, x: window.top.screenX || window.top.screenLeft, y: window.top.screenY || window.top.screenTop}

    // set window size if percent
    if(typeof size.w === 'string' && size.w.endsWith('%')){size.w = Number(size.w.replace(/%$/, ''))*win.w.o/100;}
    if(typeof size.h === 'string' && size.h.endsWith('%')){size.h = Number(size.h.replace(/%$/, ''))*win.h.o/100;}

    // set window size if ratio
    if(typeof size.w === 'string' && size.w.includes(':')){
        size.w = size.w.split(':', 2);
        if(win.w.o < win.h.o){
            // if height is bigger than width, reverse ratio
            size.w = Number(size.h)*Number(size.w[1])/Number(size.w[0]);
        }else{size.w = Number(size.h)*Number(size.w[0])/Number(size.w[1]);}
    }
    if(typeof size.h === 'string' && size.h.includes(':')){
        size.h = size.h.split(':', 2);
        if(win.w.o < win.h.o){
            // if height is bigger than width, reverse ratio
            size.h = Number(size.w)*Number(size.h[0])/Number(size.h[1]);
        }else{size.h = Number(size.w)*Number(size.h[1])/Number(size.h[0]);}
    }

    // force window size to type number
    if(typeof size.w === 'string'){size.w = Number(size.w);}
    if(typeof size.h === 'string'){size.h = Number(size.h);}

    // keep popup window within padding of window size
    if(size.w > win.w.i-50){size.w = win.w.i-50;}
    if(size.h > win.h.i-50){size.h = win.h.i-50;}

    // do math
    const x = win.w.o / 2 + win.x - (size.w / 2);
    const y = win.h.o / 2 + win.y - (size.h / 2);
    return window.open(url, title, `width=${size.w},height=${size.h},left=${x},top=${y}${options}`);
}

การใช้งาน:

// width and height are optional (defaults: width = '75%' height = '16:9')
popupWindow('https://www.google.com', 'Title', '75%', '16:9', {/* options (optional) */});

// options can be an object, array, or string

// example: object (only in object, true/false get replaced with 'yes'/'no')
const options = {scrollbars: false, resizable: true};

// example: array
const options = ['scrollbars=no', 'resizable=yes'];

// example: string (same as window.open() string)
const options = 'scrollbars=no,resizable=yes';

1
function fnPopUpWindow(pageId) {
     popupwindow("hellowWorld.php?id="+pageId, "printViewer", "500", "300");
}

function popupwindow(url, title, w, h) {
    var left = Math.round((screen.width/2)-(w/2));
    var top = Math.round((screen.height/2)-(h/2));
    return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, '
            + 'menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w 
            + ', height=' + h + ', top=' + top + ', left=' + left);
}
<a href="javascript:void(0);" onclick="fnPopUpWindow('10');">Print Me</a>

หมายเหตุ: คุณต้องใช้Math.roundเพื่อรับจำนวนเต็มความกว้างและความสูงที่แน่นอน


0

อ้างอิงจาก Facebook แต่ใช้เคียวรีสื่อแทนการลงทะเบียนตัวแทนผู้ใช้เพื่อคำนวณถ้ามีพื้นที่เพียงพอ (มีที่ว่าง) สำหรับป๊อปอัพไม่เช่นนั้นจะเต็มหน้าจอ Tbh ป๊อปอัปบนมือถือเปิดเป็นแท็บใหม่อยู่ดี

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

0

โซลูชันไฮบริดนี้เหมาะกับฉันทั้งในการตั้งค่าหน้าจอเดียวและสองหน้าจอ

function popupCenter (url, title, w, h) {
    // Fixes dual-screen position                              Most browsers      Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
    const left = (window.screen.width/2)-(w/2) + dualScreenLeft;
    const top = (window.screen.height/2)-(h/2) + dualScreenTop;
    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);
}

0

ฉันมีปัญหากับการจัดกึ่งกลางหน้าต่างป๊อปอัพในจอภาพภายนอกและwindow.screenXและwindow.screenYเป็นค่าลบ (-1920, -1200) ตามลำดับ ฉันได้ลองวิธีการแก้ปัญหาที่แนะนำข้างต้นทั้งหมดแล้วและทำงานได้ดีในหน้าจอหลัก ฉันอยากจากไป

  • ระยะขอบ 200 px สำหรับซ้ายและขวา
  • ระยะขอบ 150 px สำหรับด้านบนและด้านล่าง

นี่คือสิ่งที่ทำงานให้ฉัน:

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

-4

.center{
    left: 50%;
    max-width: 350px;
    padding: 15px;
    text-align:center;
    position: relative;
    transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);   
}

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.