// 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);
Дело в том, что window.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);
})
}