模拟alert,confirm,prompt
以前项目上用的那个虽然也是自己写的,但是是基于JQ的,前不久看到人人网出的JS有道考题和这个很像,所以就用原生JS重写了一遍:
JS
(function(win){ var tips = { 'title':'信物宝提示', 'enter':'确定', 'cancel':'取消', 'close':'关闭' }, isIE6 = !window.XMLHttpRequest, cssLoaded = false, isOpen = false, loadCss = function(){ if(cssLoaded) return; var cssHref = 'dialog.css'; var style = document.createElement('link'); style.type = 'text/css'; style.rel = 'stylesheet'; style.href = cssHref; document.getElementsByTagName('head')[0].appendChild(style); cssLoaded = true; }; /*************************************对外提供的接口****************************************************/ var dialog = function(opts){ return new dialog.prototype.init(opts); }; dialog.prototype = { constructor:dialog, init:function(opts){ loadCss(); }, alert:function(opts){ var _this = this; var set = extend({ width:400, height:100 },opts||{}); if(isOpen) this.close(); isOpen = true; this.doms = createElements(set); this.doms.contentBox.appendChild(document.createTextNode(opts.content)); setCenter(this.doms); this.doms.btnEnter.onclick = function(){ _this.close(); opts.callback && opts.callback(true); }; this.doms.contentTitle.onmousedown = function(e){ var mousePos= getMousePos(e),pos = getElementPos(_this.doms.contentOuter); var _move = move(mousePos,_this.doms.contentOuter,pos.y,pos.x); addEvent(document,'mousemove',_move); addEvent(document,'mouseup',function(){ removeEvent(document,'mousemove',_move) }); }; this.doms.contentTitle.ondragstart = function(){ return false;}; this.doms.close.onclick = function(){ _this.close(); }; addEvent(window,'resize',function(){setCenter(_this.doms);}) }, confirm:function(opts){ var _this = this; this.alert(opts); this.doms.btnBox.appendChild(this.doms.btnCancel); this.doms.btnCancel.onclick = function(){ _this.close(); opts.callback && opts.callback(false); } }, prompt:function(opts){ var _this = this,input; this.alert(opts); input = createEl('<input type="text" name="" value="'+opts.defaultValue+'" id="diaglo_prompt_input"/>',this.doms.contentBox); input.select(); this.doms.btnBox.appendChild(this.doms.btnCancel); this.doms.btnEnter.onclick = function(){ _this.close(); opts.callback && opts.callback(input.value); }; this.doms.btnCancel.onclick = function(){ _this.close(); opts.callback && opts.callback(null); }; this.doms.close.onclick = function(){ _this.close(); }; }, load:function(opts){ var _this = this; this.alert(opts); this.doms.contentOuter.removeChild(this.doms.btnBox); this.doms.btnEnter.onclick = null; ajax({ url:opts.content, success:function(data){ _this.doms.contentBox.innerHTML = data; opts.callback && opts.callback(data); } }) }, loadIframe:function(opts){ var _this = this,iframe = document.createElement('iframe'); this.alert(opts); this.doms.contentOuter.removeChild(this.doms.btnBox); this.doms.btnEnter.onclick = null; iframe.src = opts.content; iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.frameborder = '0' _this.doms.contentBox.innerHTML = ''; _this.doms.contentBox.appendChild(iframe); iframe.attachEvent ? (iframe.attachEvent = _load) : (iframe.onload = _load); function _load(){ opts.callback && opts.callback(iframe); }; }, close:function(){ var db = document.body; db.removeChild(this.doms.overlayer); db.removeChild(this.doms.contentOuter); isIE6 && db.removeChild(this.doms.overlayIframe); this.doms.btnEnter.onclick = this.doms.btnCancel.onclick = this.doms.close.onclick = this.doms.contentTitle.onmousedown = null; this.doms = null; isOpen = false; } }; dialog.prototype.init.prototype = dialog.prototype; win.regMethod = function(scope,handler){ return scope[handler]= dialog(); }; /**********************************私有方法*******************************************************/ function extend(subClass,superClass){ for(var key in superClass) subClass[key] = superClass[key]; return subClass; }; function createElements(opts){ var db = document.body,h = Math.max(document.documentElement.clientHeight,document.body.offsetHeight); var width = opts.width,height = opts.height; var overlayer = createEl('<div id="dialog_overlayer" style="position:absolute;top:0;left:0;width:100%;height:'+h+'px;background:#000;opacity:.5;filter: Alpha(Opacity=50);"></div>',db), overlayIframe = isIE6 && createEl('<iframe marginwidth="0" marginheight="0" align="top" scrolling="no" frameborder="0" class="dialog_HideSelect" src="" style="position:absolute;top:0;left:0;width:100%;height:'+h+'px;filter: Alpha(Opacity=0);"></iframe>',db), contentOuter = createEl('<div id="dialog_window" style="position:fixed;_position:absolute;top:50%;left:50%;width:'+width+'px;"></div>',db), contentTitle = createEl('<div id="dialog_title"><h3>'+ (opts.title || tips.title) +'</h3></div>',contentOuter), close = createEl('<a href="#" id="dialog_btn_close" >'+ tips.close +'</a>',contentTitle), contentBox = createEl('<div id="dialog_Content" style="height:'+height+'px;"></div>',contentOuter), btnBox = createEl('<div id="dialog_btnBox"></div>',contentOuter), btnEnter = createEl('<button type="button" id="dialog_btn_enter">'+ (opts.enter||tips.enter) +'</button>',btnBox), btnCancel = createEl('<button type="button" id="dialog_btn_cancel">'+(opts.cancel|| tips.cancel) +'</button>') return { overlayer:overlayer, overlayIframe:overlayIframe, contentOuter:contentOuter, contentTitle:contentTitle, close:close, contentBox:contentBox, btnBox:btnBox, btnEnter:btnEnter, btnCancel:btnCancel }; }; function createEl(str,parent){ var div = document.createElement('div'),el; div.innerHTML = str; el = div.firstChild; return parent ? parent.appendChild(el) : el; }; function setCenter(doms){ var T = doms.contentOuter,w = T.offsetWidth,h = T.offsetHeight,timer = null; var dd = document.documentElement,W = dd.clientWidth,H = dd.clientHeight; T.style.top = (H-h)/2+'px'; T.style.left = (W-w)/2+'px'; if(isIE6){ window.onscroll = function(){ if(timer) clearTimeout(timer); timer = setTimeout(function(){ var t = Math.max(document.body.scrollTop,document.documentElement.scrollTop); T.style.top = (t+H-h)/2+'px'; },100); } } }; function getMousePos(e){ e = e || window.event; if(e.pageX || e.pageY) return { left:e.pageX,top:e.pageY}; return { left:e.clientX + document.documentElement.scrollLeft - document.body.clientLeft, top:e.clientY + document.documentElement.scrollTop - document.body.clientTop }; }; function addEvent(el,type,fn){ if(el.addEventListener != undefined){ el.addEventListener(type,fn,false); }else if(el.attachEvent != undefined){ el.attachEvent('on'+type,fn) }else{ el['on'+type] = fn; }; }; function removeEvent(el,type,fn){ if(el.removeEventListener != undefined){ el.removeEventListener(type,fn,false); }else if(el.detachEvent != undefined){ el.detachEvent('on'+type,fn); }else{ el['on'+type] = function(){}; }; }; function move(oldPos,target,t,l){ return function(e){ var newPos = getMousePos(e); target.style.top = t + (newPos.top - oldPos.top) + 'px'; target.style.left = l + (newPos.left - oldPos.left) + 'px'; }; }; function getElementPos(el){ var x = 0,y=0; if(el.getBoundingClientRect){ var pos = el.getBoundingClientRect(); var d_root = document.documentElement,db = document.body; x = pos.left + Math.max(d_root.scrollLeft,db.scrollLeft) - d_root.clientLeft; y = pos.top + Math.max(d_root.scrollTop,db.scrollTop) - d_root.clientTop; }else{ while(el != db){ x += el.offsetLeft; y += el.offsetTop; el = el.offsetParent; }; }; return { x:x, y:y }; }; function ajax(opts){ var xhr = null; var set = extend({ type:'GET', url:'' },opts||{}); if(typeof window.XMLHttpRequest != 'undefined'){ xhr = new window.XMLHttpRequest(); }else{ xhr = new ActiveXObject('MSXML2.XmlHttp.6.0'); }; xhr.open(set.type,set.url); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status >= 200 && xhr.status <= 304 ){ set.success && set.success(xhr.responseText); }else{ set.failure && set.failure(xhr.status); }; }; }; xhr.send(null); } })(window);
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title></title> </head> <body style="height:2000px;"> <input type="button" name="" value="alert" id="btn_alert" /> <input type="button" name="" value="confirm" id="btn_confirm" /> <input type="button" name="" value="prompt" id="btn_prompt" /> <input type="button" name="" value="load" id="btn_load" /> <input type="button" name="" value="loadIframe" id="btn_loadIframe" /> <select> <option name="" value="1">test</option> <option name="" value="1">test</option> <option name="" value="1">test</option> </select> <script type="text/javascript" src="dialog.js"></script> <script type="text/javascript"> var btn_alert = document.getElementById('btn_alert'), btn_confirm = document.getElementById('btn_confirm'), btn_prompt = document.getElementById('btn_prompt'), btn_load = document.getElementById('btn_load'), btn_loadIframe = document.getElementById('btn_loadIframe'); regMethod(window,'sbi'); btn_alert.onclick = function(){ sbi.alert({ 'content':'你现在测试的是alert!' }) }; btn_confirm.onclick = function(){ sbi.confirm({ 'content':'你现在测试的是confirm!', 'callback':function(v){alert(v)} }) }; btn_prompt.onclick = function(){ sbi.prompt({ 'content':'你现在测试的是prompt!', 'defaultValue':"说点什么吧,亲!", 'callback':function(v){alert(v)} }) }; btn_load.onclick = function(){ sbi.load({ 'content':'loadTest.html', 'callback':function(v){alert('内容加载完成!')} }) }; btn_loadIframe.onclick = function(){ sbi.loadIframe({ 'content':'http://www.baidu.com', 'height':300, 'width':500, 'callback':function(v){alert('iframe内容加载完成!')} }) }; </script> </body> </html>
CSS:
* {padding: 0;margin: 0;} body {font-family: ;font-size: 12px;} #dialog_window{ background: #fff; width: 400px;border: 2px solid #999;} #dialog_title {background: #f8f8f8; padding: 0 10px; height: 36px; line-height: 36px; text-align: right; cursor: move;} #dialog_title h3 {font-size: 12px; color: #333; float: left;} a#dialog_btn_close { color: #333; text-decoration: none;} #dialog_Content { padding: 10px; clear: both;} #dialog_btnBox {padding: 5px 0; background: #f8f8f8; text-align: center;} #dialog_btn_enter, #dialog_btn_cancel { display: inline-block; *display: inline; *zoom:1; padding: 5px 15px; background: blue; color: #fff;margin-right: 10px;border: 0;} #diaglo_prompt_input { display:block; border: 1px solid #ddd; padding: 5px; width:90%; margin: 8px 0;}
说明:对外提供了alert,confirm,prompt,load,loadIframe,close 6个方法,前三种不需要解释了吧,load方法就是用ajax加载一个HTML代码片断,loadIframe就是加载一个iframe了,close则是关闭当前显示的弹窗。
注意:为了避免命名冲突,我这里写了一个注册命名空间的函数regMethod,比如你取个名字为fuck,那么在调用alert等方法之前要调用 regMethod(window,'fuck');这样就可以这样调用fuck.alert(),fuck.confirm(),又比如你有自己的JS库,有自己的对象,你也可以直接把它注册到你的对象上var xx00 = {}, regMethod(window,xx00['dialog']);这样就可以通过xxoo.dialog.alert(),xxoo.dialog.confirm()来调用了。