js定义:html
/** * 弹窗类,可继承 */ var Dialog = { /** * 静态属性 */ //记录当前dialog个数 dialogCounts: 0, /** * 构造函数 * @param w 弹窗的宽度,单位px * @param h 弹窗的高度,单位px * @param html 弹窗内容,格式html */ creat: function(w,h,html) { /** * 私有属性 */ var ww = w || 300; var hh = h || 200; //获取浏览器可视区域宽高 var winSize = function() { var e = window, a = 'inner'; if (!('innerWidth' in window )){ a = 'client'; e = document.documentElement || document.body; } return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }; }; //遮罩层 var newDom = document.createElement("div"); newDom.className = "webo_shade"; newDom.style.position = "absolute"; newDom.style.top = "0"; newDom.style.left = "0"; newDom.style.height = document.body.scrollHeight+"px"; newDom.style.width = document.body.scrollWidth+"px"; newDom.style.backgroundColor = "#000"; newDom.style.filter = "alpha(opacity=50)"; newDom.style.opacity = "0.5"; newDom.style.zIndex = "998"; newDom.style.display = "none"; document.body.appendChild(newDom); //dialg层 var windowWidth = winSize().width; var windowHeight = winSize().height; var dWin = document.createElement("div"); dWin.className = "webo_dialog"; dWin.style.position = "fixed"; if (w > windowWidth) { dWin.style.left = "0"; } else { dWin.style.left = (windowWidth - ww)/2 + "px"; } if (h > windowHeight) { dWin.style.top = "0"; }else{ dWin.style.top = (windowHeight - hh)/2 + "px"; } dWin.style.width = ww+"px"; dWin.style.height = hh+"px"; dWin.style.backgroundColor = "#FFF"; dWin.style.zIndex = "999"; dWin.style.display = "none"; dWin.innerHTML = html || "there is nothing."; newDom.appendChild(dWin); //关闭 var clo = document.createElement("span"); clo.className = "webo_dialog_close"; clo.style.position = "absolute"; clo.style.top = "1px"; clo.style.right = "4px"; clo.title = "关闭"; clo.style.fontSize = "18px"; clo.style.cursor = "pointer"; clo.innerHTML = "×"; dWin.appendChild(clo); //关闭按钮监听 if(clo.addEventListener){ clo.addEventListener("click",function(e){ if (window.event != undefined) { window.event.cancelBubble = true; } else if (e.stopPropagation) { e.stopPropagation(); } example.kill(); },false); }else if(clo.attachEvent){ clo.attachEvent("onclick",function(e){ if (window.event != undefined) { window.event.cancelBubble = true; } else if (e.stopPropagation) { e.stopPropagation(); } example.kill(); }); } //实例化对象 var example = {}; example.show = function(){ newDom.style.display = "block"; dWin.style.display = "block"; }; example.hide = function(){ dWin.style.display = "none"; newDom.style.display = "none"; }; example.kill = function(){ newDom.removeChild(dWin); document.body.removeChild(newDom); Dialog.dialogCounts--; }; example.test = function() { alert("高度:"+pageHeight()); } this.dialogCounts++; //返回实例化的对象 return example; } }
页面调用:web
var t = Dialog.creat(); t.show(); var t1 = Dialog.creat(400,300,"hehe"); t1.show(); var t2 = Dialog.creat(400,300,"<p>hehe</p>"); t2.show(); alert(Dialog.dialogCounts); //3