window.showModalDialog() 的替代方案
window.showModalDialog() 是 IE 很早就提出并最早实现的“弹出窗口”方法,它与 window.open() 的区别主要在 有无原生返回值、子窗口能否锁定父窗口,所以它的学名叫【模态窗口】。
虽然后来的主流浏览器 都相继实现了这个非标准方法,但自从 HTML5 掀起了全球网页浏览器标准化浪潮,它们又在逐渐废弃这个方法。
但有时,比 alert()、confirm()、prompt() 更能自由定制的 网页弹出窗口 还是蛮有用的(比如 知乎的第三方网站账号登录),我们就自己封装吧 ——
//
// iModalDialog.js v0.3
//
(function (BOM, DOM, $) {
function iOpen(URL, Scale, CallBack) {
Scale = (Scale > 0) ? Scale : 3;
var Size = {
height: BOM.screen.height / Scale,
width: BOM.screen.width / Scale
};
var Top = (BOM.screen.height - Size.height) / 2,
Left = (BOM.screen.width - Size.width) / 2;
var new_Window = BOM.open(URL, '_blank', [
'top=' + Top, 'left=' + Left,
'height=' + Size.height, 'width=' + Size.width,
'resizable=no,menubar=no,toolbar=no,location=no,status=no,scrollbars=no'
].join(','));
if (CallBack)
var Timer = setInterval(function () {
if (new_Window.closed) {
CallBack.call(BOM, new_Window);
clearInterval(Timer);
}
}, 200);
return new_Window;
}
var $_Cover = $('<div id="iModalDialog_Cover" />').css({
position: 'absolute',
'z-index': 2147483640,
top: 0,
left: 0,
width: '100%',
height: '100%',
background: 'black',
opacity: 0.5,
display: 'none'
}).appendTo(DOM.body);
$.fn.iModalDialog = function () {
var Args = Array.prototype.slice.call(arguments, 0);
var URL = Args.shift();
if (! isNaN( Number(Args[0]) ))
var Scale = Args.shift();
if (typeof Args[0] == 'string')
var Event = Args.shift();
if (typeof Args[0] == 'function')
var CallBack = Args.shift();
this.bind(Event || 'click', function (EO) {
$_Cover.show();
var NW = iOpen.call(BOM, URL, Scale, function () {
$_Cover.hide();
});
$_Cover.click(function () {
NW.focus();
});
if (CallBack) CallBack.call(this, EO, NW);
return false;
});
};
})(self, self.document, self.jQuery);
主要特性
- 直接绑定页面元素的用户事件(现代浏览器会拦截非用户操作而打开的新窗口),默认绑定
click
,但可指定绑定其它类型,并设置事件回调 - 弹出窗口自动在屏幕居中,其尺寸可由“一分之几”形式的参数设置
- 弹窗后,父窗口启动全局半透明遮蔽层,用户点击父窗口将让弹窗活动焦点