通常在一般的业务场景下,我们都是传入一个url,打开一个新窗口就完事了,但是...
第三方登录弹窗应用场景
产品其实是想在本页面弹窗起来,用户就算不登录也可以立即关掉,而不影响页面的浏览,增加用户留存。效果就是点击qq登录,这个时候弹一个窗口,而这个窗口是一个独立的web窗口(并非iframe,为啥不用iframe,iframe本身问题比较多能不用尽量不用),怎么实现这个效果(具体效果可以看爱奇艺官网的三方登录),我们找找window.open的官方文档。
let windowObjectReference = window.open(strUrl, strWindowName, [strWindowFeatures]);
strUrl === 要在新打开的窗口中加载的URL。
strWindowName === 新窗口的名称。
strWindowFeatures === 一个可选参数,列出新窗口的特征(大小,位置,滚动条等) 的为一个DOMString
[`DOMString`](https://developer.mozilla.org/zh-CN/docs/Web/API/DOMString "DOMString 是一个UTF-16字符串。由于JavaScript已经使用了这样的字符串,所以DOMString 直接映射到 一个String。")。
出处:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/open
所以其实重点就在这个 strWindowFeatures, 其实他就是一个字符串,只不过是把参数拼接起来的字符串,下面我示例一个比较常用的几个参数
window.open(getUrl, '_blank', `width=${width}, height=${height}, left=${left}, top=${top}`);
一眼就看明白了,无非是高宽,定位左和上的值,按正常来理解我们这时候希望弹一个居中的弹窗怎么做,很简单。
function createOpen () {
const width = 300
const height = 300
let left = (window.innerWidth- width) / 2
let top = (window.innerHeight- height ) / 2
window.open('http://www.baidu.com', '_blank', `width=${width}, height=${height}, left=${left}, top=${top}`);
}
我们发现似乎弹窗没有什么问题,但是如果我们是双屏的设备,你把网页拖到右边的显示器,再试试?
然后我们发现怎么就不居中了呢... left的设置似乎不生效了?
百思不得其解之后,我们再看一下官方对于left的解释。
Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
定位相对于当前用户操作系统的work area的最左边的值。且,不能超出初始化屏幕之外。
似乎明白了,原来left是相当于操作系统的左侧,而不是当前浏览器窗口的左侧。 那么如何解决这个问题呢,只需要判断当前浏览器窗口距离操作系统的偏移值,在原来的left的基础上+这个偏移值就可以解决了。
function createOpen () {
const width = 300
const height = 300
let left = (window.innerWidth-width)/2 + (window.screenX ? window.screenX: window.screenLeft)
let top = (window.innerHeight- height ) / 2 + (window.screenY ? window.screenY: window.screenTop) + (window.outerHeight - window.innerHeight)
window.open('http://www.baidu.com', '_blank', `width=${width}, height=${height}, left=${left}, top=${top}`);
}
细心的同学发现为什么top那里+了一个(window.outerHeight - window.innerHeight)呢,这是因为我们的浏览器一般上面有一个很宽的菜单栏,innerHeight是没有算上面的值的,所以要算上这个值,让上下居中更加准确。
这样处理之后,无论是拖动窗口还是缩小放大窗口, 都没有问题了。