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