js单例模式--实现点击只有一个弹窗
1 <head> 2 <meta charset="UTF-8"> 3 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 4 <title>Document</title> 5 <style> 6 .model { 7 width: 200px; 8 height: 200px; 9 border: 1px solid aqua; 10 position: fixed; 11 top: 50%; 12 left: 50%; 13 transform: translate(-50%, -50%); 14 text-align: center; 15 } 16 </style> 17 </head> 18 19 <body> 20 <div id="loginBtn">点我</div> 21 <script> 22 var getSingle = function (fn) { 23 var result; //缓存实例 24 return function () { 25 return result || (result = fn.apply(this, arguments)) 26 } 27 } 28 var createLoginLayer = function () { 29 var oDiv = document.createElement("div"); 30 oDiv.innerHTML = "我是登录浮窗"; 31 oDiv.className = "model"; 32 oDiv.style.display = "none"; 33 document.body.appendChild(oDiv); 34 return oDiv; 35 } 36 var createSingleLoginLayer = getSingle(createLoginLayer); 37 document.getElementById("loginBtn").onclick = function () { 38 //动态创建弹窗 39 //新建一个弹窗实例,内部使用单例模式管理,一直只能有一个. 40 var loginLayer = createSingleLoginLayer(); 41 loginLayer.style.display = "block" 42 } 43 </script> 44 </body>