原生js实现弹出层

利用原生js的元素创建、添加,手写一个弹出层
话不多说,先上效果:

可以设置弹出层的类型、宽度、高度、标题、内容区。
弹出层默认为1,不自动消失的弹出层,类型为2时,默认3s关闭的提示框。

content可以存放字符串以及dom元素。
js代码:

class layui {
  callBack;
  zDiv;
  time;
  ids;
  constructor() {}

  open(options = {}) {
    var {
      type = 1,
      tittle,
      content,
      width = 400,
      height = 300,
      callBack,
      time = 3000,
    } = options;
    this.callBack = callBack;
    this.time = time;
    this.zDiv = this.ce("div", {
      width: document.documentElement.clientWidth + "px",
      height: document.documentElement.clientHeight + "px",
      position: "fixed",
      top: 0,
      backgroundColor: "rgba(160,160,160,0.4)",
    });

    // this.zDiv.className = "closes";
    var div = this.ce("div", {
      width: width + "px",
      height: height + "px",
      position: "absolute",
      top: "50%",
      left: "50%",
      transform: "translate(-50%,-50%)",
      backgroundColor: "#FFF",
      boxSizing: "border-box",
      // padding:"10px"
    });
    var title = this.ce("div", {
      width: "100%",
      borderBottom: "1px solid #ccc",
      textAlign: "center",
      height: "40px",
      lineHeight: "40px",
      backgroundColor: "#f8f8f8",
    });
    title.textContent = tittle;

    div.appendChild(title);
    var bDiv = this.ce("div", {
      width: "100%",
      height: height - 90 + "px",
      padding: "15px",
      backgroundColor: "#eee",
      boxSizing: "border-box",
    });

    if (content instanceof HTMLElement) {
      var contents = content.cloneNode(true);
      bDiv.appendChild(contents);
    } else {
      bDiv.innerHTML = content;
    }
    div.appendChild(bDiv);

    var fDiv = this.ce("div", {
      width: "100%",
      height: "50px",
    });
    var btn = this.ce("button", {
      height: "30px",
      width: "80px",
      backgroundColor: "#1E9FFF",
      color: "#FFF",
      textAlign: "center",
      lineHeight: "30px",
      fontSize: "14px",
      border: "none",
      borderRadius: "5px",
      padding: "0",
      float: "right",
      margin: "10px 20px 0 0 ",
      outline: "none",
    });
    btn.textContent = "确认";
    btn.className = "closes";
    fDiv.appendChild(btn);
    div.appendChild(fDiv);

    this.zDiv.appendChild(div);
    this.zDiv.addEventListener("click", this.close.bind(this));
    document.documentElement.appendChild(this.zDiv);
    if (type == 2) {
      var that = this;
      this.ids = setTimeout(function () {
        clearTimeout(that.ids);
        that.zDiv.remove();
      }, this.time);
    }
  }
  close(e) {
    if (e.target.className !== "closes") {
      return;
    } else {
      this.callBack && this.callBack();
      this.zDiv.remove();
    }
  }
  ce(type, style) {
    var item = document.createElement(type);
    Object.assign(item.style, style);
    return item;
  }
}

使用方法:

layer.open({
    tittle:"提示框",
    type:2,
    content:msg,
    width:300,
    height:200,
    time:2000
})

你可能感兴趣的:(HTML5)