// 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))
}
Называйте это как следующий, и он откроется поверх текущего окна
popup('http://www.google.com', 'my-win');
Или сделать его немного смещена
popup('http://www.google.com', 'my-win', 30, 30);
Дело в том, что окно. screenX/screenLeft дает вам позицию в отношении всего рабочего стола, а не только монитора.
window.screen.left был бы идеальным кандидатом для предоставления вам необходимой информации. Проблема в том, что она задается при загрузке страницы, и пользователь может переместить окно на другой монитор.
Дополнительные исследования
Окончательное решение этой проблемы (вне только компенсируя от текущей позиции), требуется знать размеры экрана, что окно находится. Поскольку экранный объект не обновляется пользователь перемещает окно вокруг, нам нужно создать собственный способ определения текущего разрешения экрана. Вот что я придумал
/**
* 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();
};
Так что если вы хотите, чтобы всегда открыть окно в левом верхнем углу любой монитор окно, вы можете использовать следующее:
function openAtTopLeftOfSameMonitor(url, winName) {
getScreenProps(function(scr){
window.open(url, winName, 'top=0,left=' + scr.left);
})
}
ни одна из этих работ «решения» для меня. Вы нашли какой-то способ. – oma 2012-10-07 15:29:10
@oma Я предоставил решение, которое работает для меня, ответил в этом сообщении, хотя: http://stackoverflow.com/questions/6911138/position-javascript-window-open-centered-on-secondary-screen/14269826# 14269826 – 2013-01-11 00:36:17
вы должны были разместить здесь здесь. Другой - это dup, и этот поток имеет более релевантный контекст. – oma 2013-01-11 16:44:59