JavaScript案例:div对话框(动态创建,封装) 作者:马育民 • 2022-08-05 18:35 • 阅读:10030 # 说明 使用时只需要引入 `.js` 文件即可 ### 技术难度 - js 动态引入 `.css` 文件 - 循环绑定事件,需要用到函数封装 或 闭包 # 代码 ### css 文件 ``` .window{ width: 300px; margin: 0 auto; border: 1px solid #999; background-color: #fff; display: none; position:absolute; z-index: 100; } .windowBg{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: black; opacity: 0.3; display: none; } .win-title{ height: 50px; line-height: 50px; padding: 0 10px; border-bottom: 1px solid #c5c5c5; color: #333; border-radius: 2px 2px 0 0; } .win-info{ padding: 20px; line-height: 24px; } .win-bottom{ text-align: right; padding: 0 15px 10px 0px; } .win-btn{ display: inline-block; border-color: #1E9FFF; background-color: #1E9FFF; color: #fff; width: 60px; height: 30px; text-align: center; } ``` ### js文件 ``` /* * 显示对话框 * title:对话框标题 * msg:对话框显示的提示信息 * btns:数组结构,定义按钮的文字内容 * funs:数组结构,元素是函数对象,与按钮向对应的事件函数 */ var dialog = (function(){ // 引入dialog.css function initCSS(){ var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = "./css/dialog.css"; var head = document.getElementsByTagName("head")[0]; head.appendChild(link); } // 有了自调用函数,这些变量就是函数内部变量 // 如果不用自调用函数,就变成全局变量了 var body = null var win = null var winBg = null function open(winTitle,msg,btns,funs){ body = document.getElementsByTagName("body")[0] win = document.createElement("div") body.appendChild(win) win.className="window" var title = document.createElement("div") title.className = "win-title" title.innerHTML = winTitle win.appendChild(title) var info = document.createElement("div") info.className = "win-info" info.innerHTML = msg win.appendChild(info) var bottom = document.createElement("div") bottom.className = "win-bottom" win.appendChild(bottom) var i = 0 btns.forEach(function(e){ var btn = document.createElement("button") btn.className = "win-btn" btn.innerHTML = e bottom.appendChild(btn) // bindClick(btn,funs[i]) btn.onclick = bindClick(funs[i]) i++ }) winBg = document.createElement("div") body.appendChild(winBg) winBg.className="windowBg" winBg.style.display = "block" winBg.onclick = function(e){ closeWin() } win.style.display = "block" win.style.top = (window.innerHeight - win.clientHeight )/2+"px" win.style.left = (window.innerWidth - win.clientWidth )/2+"px" } // 实现简单的提示信息对话框 // 目的:简化调用 open() 函数 function alert(msg,callback){ open("提示",msg,["确定"],[callback]) } function confirm(msg,callback){ open("提示",msg,["是","否"],[callback,function(){}]) } function closeWin(){ body.removeChild(win) body.removeChild(winBg) } // 循环绑定事件方式一:套一层函数 // function bindClick(btn,f){ // btn.onclick = function(){ // f() // closeWin() // } // } // 循环绑定事件方式二:闭包 function bindClick(f){ return function(){ closeWin() f() } } initCSS() // 返回的对象,对象里面是公开的方法 // 类似java,暴露出公共的方法,其他方法是私有的,不让外部调用 return { open:open, alert:alert, confirm:confirm } })() ``` ### html ``` Document ``` 原文出处:http://malaoshi.top/show_1IX3o9WsHlR3.html