<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h3>创建唯一的窗口</h3>
<button type="button" id="btn1">创建div1</button>
<script>
  //管理单例
  var getSingle = function(fn) {
    var result;
    return function() {
      return result || (result = fn.apply(this.arguments));
    }
  }
  function LayerAction(){
    this.layer = null;
    if (typeof this.setLayer !== "function") { // 判断 ?
      LayerAction.prototype.setLayer = function(layer) {
        if (!layer) {
          console.error("error");
          return;
        } else {
          this.layer = layer;
        }
      };

      LayerAction.prototype.showLayer = function(){
        this.layer.style.display = "block";
      };
      LayerAction.prototype.closeLayer = function(){
        this.layer.style.display = "none";
      };
    }
  }

  var div1 = {
    div1Layer: null,
    layerAction: new LayerAction(),

    createDiv1Layer: function(){
      var div=document.createElement("div");
      div.innerHTML="我是div1";
      div.style.display = 'none';
      div.id = 'div1';
      document.body.appendChild(div);
      var closeBtn = document.createElement('span');
      closeBtn.innerText='关闭';
      closeBtn.id="closeDiv1";
      div.appendChild(closeBtn);
      return div;
    },

    createDiv1Style:function(){
      var styleElement = document.createElement('link');
      styleElement.type = 'text/css';
      styleElement.href = 'div1.css';
      styleElement.rel = 'stylesheet';
      document.getElementsByTagName('head')[0].appendChild(styleElement);
      return styleElement
    },

    bindActionForCloseLayer: function(){
      var that = div1;
      document.getElementById('closeDiv1').onclick = function(){
        that.layerAction.closeLayer();
      }
    },

    startDiv1Layer: function () {
      var createDiv1singleLayer = getSingle(this.createDiv1Layer);
      var createDiv1singleStyle = getSingle(this.createDiv1Style);
      var bindCloseEvent = getSingle(this.bindActionForCloseLayer);
      var that = this;
      document.getElementById('btn1').onclick = function(){
        createDiv1singleStyle();
        that.div1Layer = createDiv1singleLayer();
        that.layerAction.setLayer(that.div1Layer);
        that.layerAction.showLayer();
        bindCloseEvent();
      }
    }
  };
  div1.startDiv1Layer();
</script>
</body>
</html>

 div1.css

#div1{
  width: 500px;
  height: 300px;
  background: #0b0a0a;
  color: #fff;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
#closeDiv1{
  cursor: pointer;
  margin-right: 5px;
  margin-top: 5px;
  float: right;
  border: 1px solid #fff;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2021-09-21
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
相关资源
相似解决方案