// Pops a window relative to the current window position
function popup(url, winName, xOffset, yOffset) {
var x = (window.screenX || window.screenLeft || 0) + (xOffset || 0);
var y = (window.screenY || window.screenTop || 0) + (yOffset || 0);
return window.open(url, winName, 'top=' +y+ ',left=' +x))
}
Gọi nó như sau và nó sẽ mở ra trên cùng của cửa sổ hiện tại
popup('http://www.google.com', 'my-win');
Hoặc làm cho nó một chút bù đắp
popup('http://www.google.com', 'my-win', 30, 30);
Vấn đề là cửa sổ đó. screenX/screenLeft cho bạn vị trí trong mối quan hệ với toàn bộ màn hình, chứ không chỉ màn hình.
window.screen.left sẽ là ứng cử viên lý tưởng để cung cấp cho bạn thông tin bạn cần. Vấn đề là nó được đặt khi trang được tải và người dùng có thể di chuyển cửa sổ sang màn hình khác.
Nhiều nghiên cứu
Một giải pháp cuối cùng cho vấn đề này (ngoài chỉ bù đắp từ vị trí cửa sổ hiện hành) đòi hỏi phải biết kích thước của màn hình cửa sổ đang ở. Kể từ khi đối tượng màn hình không cập nhật khi người dùng di chuyển một cửa sổ xung quanh, chúng ta cần tạo ra cách riêng để phát hiện độ phân giải màn hình hiện tại. Dưới đây là những gì tôi đã đưa ra
/**
* Finds the screen element for the monitor that the browser window is currently in.
* This is required because window.screen is the screen that the page was originally
* loaded in. This method works even after the window has been moved across monitors.
*
* @param {function} cb The function that will be called (asynchronously) once the screen
* object has been discovered. It will be passed a single argument, the screen object.
*/
function getScreenProps (cb) {
if (!window.frames.testiframe) {
var iframeEl = document.createElement('iframe');
iframeEl.name = 'testiframe';
iframeEl.src = "about:blank";
iframeEl.id = 'iframe-test'
document.body.appendChild(iframeEl);
}
// Callback when the iframe finishes reloading, it will have the
// correct screen object
document.getElementById('iframe-test').onload = function() {
cb(window.frames.testiframe.screen);
delete document.getElementById('iframe-test').onload;
};
// reload the iframe so that the screen object is reloaded
window.frames.testiframe.location.reload();
};
Vì vậy, nếu bạn muốn luôn luôn mở cửa sổ ở phía trên bên trái của bất cứ màn hình cửa sổ đang nhập, bạn có thể sử dụng như sau:
function openAtTopLeftOfSameMonitor(url, winName) {
getScreenProps(function(scr){
window.open(url, winName, 'top=0,left=' + scr.left);
})
}
không phải là một đơn một trong những công việc 'giải pháp' đối với tôi. Bạn có tìm được cách nào không. – oma
@oma tôi đã cung cấp giải pháp phù hợp với mình, được trả lời trong bài đăng này mặc dù: http://stackoverflow.com/questions/6911138/position-javascript-window-open-centered-on-secondary-screen/14269826# 14269826 –
bạn nên đăng nó ở đây thay thế. Khác là một dup và thread này có ngữ cảnh phù hợp hơn. – oma