案例--自定义弹出层

案例 - 自定义弹出层

  + 约定

    1. 提示: skyblue, info

    2. 警告: yellow, warning

    3. 危险: red, danger

    4. 成功: green, success


js

// 以单例模式书写 自定义 弹出层
const Dialog = (function () {
  // 类 本身
  class Dialog {
    constructor () {
      // 1. 创建一个 div 标签
      this.box = document.createElement('div')
      // 添加类名
      this.box.className = 'dialog'
      // 插入页面
      document.body.appendChild(this.box)

      // 2. 设置 div 的结构样式和内容
      this.setHtml('skyblue', '我是默认文本内容', '提示')

      // 3. 事件绑定
      this.setEvent()
    }

    setHtml (color, text, info) {
      this.box.innerHTML = `
        <div class="top" style="background-color: ${ color }">${ info }
          <span>X</span>
        </div>
        <div class="content">
          ${ text }
        </div>
        <div class="bottom" style="background-color: ${ color }"></div>
      `

      // 可以在页面上出现了
      this.box.style.display = 'flex'
    }

    setEvent () {
      this.box.addEventListener('click', e => {
        e = e || widnow.event
        const target = e.target || e.srcElement

        if (target.nodeName === 'SPAN') {
          this.box.style.display = 'none'
        }
      })
    }
  }

  // 单例模式核心代码
  let instance = null
  return function (text, color) {
    if (!instance) instance = new Dialog()

    // 通过 switch 来判断 color 单词, 我们来添加一个颜色进去
    switch (color) {
      case 'danger':
        instance.setHtml('red', text, '危险')
        break
      case 'success':
        instance.setHtml('green', text, '成功')
        break
      case 'warning':
        instance.setHtml('yellow', text, '警告')
        break
      default:
        instance.setHtml('skyblue', text, '提示')
    }

    return instance
  }
})()

// 第一次使用的时候
// const d1 = new Dialog('登录成功', 'success')
// const d2 = new Dialog('登录失败', 'danger')

css

div.dialog {
  width: 400px;
  height: 230px;
  display: flex;
  flex-direction: column;
  border: 1px solid #333;

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;

  display: none;
}

.dialog > .top,
.dialog > .bottom {
  width: 100%;
  height: 40px;
  background-color: skyblue;
  box-sizing: border-box;
  line-height: 40px;
  padding-left: 20px;
  position: relative;
}

.dialog > .top > span {
  cursor: pointer;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 30px;
}

.dialog > .content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值