封装自己的alert toast

class Toast {
  constructor() {}
  // 传入的一个参数可以是一个字符串或者一个对象 
  default(org, callback) {
    let config = {
      text: '',
      tit: '提示',
      type: 'toast',
      timeOut: 1800
    }
    if (callback) {
      config.type = 'alert'
    }

    if (typeof org === 'string') {
      config.text = org
    } else {
      config.text = org.text || ''
      config.tit = org.tit || '提示'
      config.timeOut = org.timeOut || 2000
    }
    this.createElement(config, callback)
  }
// 默认有回调函数的是alert 无回调的是toast
  createElement(config, _callback) {
    if (_callback) {
      this.createAlert(config, _callback)
    } else {
      this.createToast(config)
    }
  }

  createToast(config) {
    var p = document.createElement('p')
    p.innerText = config.text
    p.setAttribute('style', this.setStyle(config))
    document.body.appendChild(p)

    // toast 自动消失
    setTimeout(() => {
      document.body.removeChild(p)
    }, config.timeOut)
  }

  createAlert(config, callback) {
    let odiv = document.createElement('div')
    odiv.style =
      'position:fixed;top:0;left:0;bottom:0;right:0;background:rgba(0,0,0,.8);'

    let boxSize =
      'width:240px;background:#fff;position:absolute;top:30%;left:50%;margin-left:-120px;border-radius:10px;'
    let fontSize =
      'padding:10px;font-size:16px;color:#000;line-height:20px;min-height:20px'
    let box =
      `<div style=` +
      boxSize +
      `>
      <h4 style='text-align:center; font-size:18px;font-weight:700;'>` +
      config.tit +
      `</h4>
        <p style=` +
      fontSize +
      `>` +
      config.text +
      `</p>
        <p style='border-top:1px solid #eee;display:flex;height:30px;line-height:30px;text-align:center;'>
          <span style='flex:1;border-right:1px solid #eee;' class='cancle'>取消</span>
          <span style='flex:1;' class='sure'>确定</span>
        </p>
    </div>`
    odiv.innerHTML = box
    document.body.appendChild(odiv)
    // alert点击box外部,取消按钮 页面alert 消失
    // 点击确定按钮执行回调, alert消失
    odiv.onclick = () => {
      document.body.removeChild(odiv)
    }

    document.querySelector('.cancle').onclick = e => {
      document.body.removeChild(odiv)
      e.stopPropagation()
    }

    document.querySelector('.sure').onclick = e => {
      e.stopPropagation()
      callback()
      document.body.removeChild(odiv)
    }
  }

  setStyle(config) {
  // toast 根据文字的长度设置div的宽度
  // 其实这个有很多办法实现,我这边主要用的是js
    let width = config.text.length * 17.5
    let css =
      'width:' +
      width +
      'px;' +
      'height:50px;line-height:50px;font-size:16px;position:fixed;top:30%;left:50%;margin-left:-' +
      width / 2 +
      'px;border-radius:10px;text-align:center;padding:0 10px;box-sizing:content-box;background:rgba(0,0,0,.5);color:#fff;border:1px solid #909399;'
    return css
  }
}
export default new Toast()
发布了45 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/cmchenmei/article/details/82191424