模拟alert,confirm,prompt
以前项目上用的那个虽然也是自己写的,但是是基于JQ的,前不久看到人人网出的JS有道考题和这个很像,所以就用原生JS重写了一遍:
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | ( 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <! 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:
1 2 3 4 5 6 7 8 9 10 | * { 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 h 3 { 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()来调用了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?