手把手教你用原生Javascript封裝一個Dialog組件

下來玩玩

Dialog component by native javascript

分析

對外暴露的方法

  • show(options) 顯示dialog
    • options 參數
      • title 標題,默認爲“”,不顯示標題
      • content 主內容,默認爲"兄弟,你好像忘記傳content的值了"
      • skin 皮膚,默認爲"",其實就是給dialog添加一個你的類名,方便重置樣式
      • btns 按鈕組,默認爲['確認'],可選['xx',‘xx’],只取前兩個作爲有效值,第一個爲confirm,第二個爲cancel
      • confirm 點擊confirm按鈕的回調,如確認
      • cancel 點擊cancel按鈕的回調,如取消
      • shadeClose 是否開啓點擊遮罩關閉,默認true
      • animation 過渡動畫,默認爲1,可選0和2,注意這裏的動畫是指內容區的動畫,最外層是固定爲0
  • hide() 關閉dialog

過渡動畫
用css3的animation,具體看下面的css

先寫好佈局、樣式(後面會移植到Javascript生成DOM)

html

<!-- 最外層 -->
<div class="dialog-wrapper">
  <!-- 居中主要層 -->
  <div class="dialog">
    <!-- 標題 -->
    <div class="title">消息提示</div>
    <!-- 主要內容 -->
    <div class="content">兄弟,你好像忘記傳content的值了</div>
    <!-- 按鈕組 -->
    <div class="buttons">
      <div class="btn cancel-btn">取消</div>
      <div class="btn confirm-btn">確認</div>
    </div>
  </div>
</div>

css

body,
html {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.dialog-wrapper {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(49, 49, 49, 0.5);
  color: #313131;
  font-size: 10px;
  -webkit-tap-highlight-color: transparent;
}

.dialog-wrapper.fadeIn {
  animation: fadeIn .2s ease;
}

.dialog-wrapper.fadeOut {
  animation: fadeOut .2s ease forwards;
}

.dialog-wrapper .dialog {
  position: relative;
  width: 85vw;
  max-width: 30em;
  border-radius: .4em;
  background-color: #fff;
  box-sizing: border-box;
  overflow: hidden;
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.1);
}

.dialog-wrapper .dialog.slideDown {
  animation: slideDown .2s ease;
}

.dialog-wrapper .dialog.slideUp {
  animation: slideUp .2s ease forwards;
}

.dialog-wrapper .dialog.scaleIn {
  animation: scaleIn 0.2s cubic-bezier(0.07, 0.89, 0.95, 1.4);
}

.dialog-wrapper .dialog.scaleOut {
  animation: scaleOut 0.2s cubic-bezier(0.07, 0.89, 0.95, 1.4) forwards;
}

.dialog-wrapper .dialog .btn {
  cursor: pointer;
}

.dialog-wrapper .dialog .btn:active {
  background-color: #f4f4f4;
}

.dialog-wrapper .dialog .close-btn {
  position: absolute;
  top: 0;
  right: 0;
  padding: 10px;
  font-size: 1.8em;
}

.dialog-wrapper .dialog .title {
  font-size: 1.8em;
  padding: 15px;
  text-align: center;
  background-color: #f4f4f4;
}

.dialog-wrapper .dialog .title:empty {
  display: none;
}

.dialog-wrapper .dialog .content {
  padding: 40px 20px;
  font-size: 1.6em;
  text-align: center;
}

.dialog-wrapper .dialog .buttons {
  font-size: 1.6em;
  display: flex;
  flex-flow: row-reverse;
}

.dialog-wrapper .dialog .buttons .btn {
  flex: 1;
  padding: 15px;
  text-align: center;
  border-top: 1px solid #ebebeb;
}

.dialog-wrapper .dialog .buttons .btn.confirm-btn {
  color: #f2d985;
}

.dialog-wrapper .dialog .buttons .btn.cancel-btn {
  color: #313131;
  border-right: 1px solid #ebebeb;
}

@keyframes slideDown {
  from {
    transform: translateY(-3em);
  }
  to {
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-3em);
  }
}

@keyframes fadeIn {
  from {
    opacity: .5;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.8);
  }
  to {
    transform: scale(1);
  }
}

@keyframes scaleOut {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(0.8);
  }
}

Javascript封裝

第一步,基本搭建
使用立即執行函數,只對外暴露兩個方法,show和hide

let dialog = (function () {

  // 節點類型
  let elem, dialog, cancelBtn, confirmBtn;

  // 動畫函數數組
  let animaArr = new Array(['fadeIn', 'fadeOut'], ['slideDown', 'slideUp'], ['scaleIn', 'scaleOut']);

  // 當前動畫類型
  let currAnimation = '';

  /**
   * @method getNeedElement 獲取所需要的節點
   */
  let getNeedElement = function () {

  }

  /**
   * @method show 顯示dialog組件
   * @param {Object} options 一系列參數
   * @returns {Object} 當前dialog節點
   */
  let show = function (options) {

  }

  /**
   * @method hide 關閉dialog組件
   */
  let hide = function (index) {

  }

  /**
   * @method bindEvent 給dialog綁定事件
   * @param {Object} confirm 確認回調
   * @param {Object} cancel 取消回調
   */
  let bindEvent = function (confirm, cancel, shadeClose) {

  }

  return {
    show,
    hide
  }

})();

第二步,編寫show方法

let show = function (options = {}) {

  // 默認參數
  let {
    title = '', content = '兄弟,你好像忘記傳content值了',
      skin = '', btns = ['確定'],
      confirm = null,
      cancel = null,
      shadeClose = true,
      animation = 1
  } = options;

  // 皮膚類名
  let skinClass = skin ? ` ${skin}` : '';

  // 給當前動畫類型賦值
  currAnimation = animation;

  // 生成按鈕
  let btnTemp = '';
  btns.forEach((item, index) => {
    if (index == 2) return;
    let btnClass = index == 0 ? 'confirm-btn' : 'cancel-btn';
    let temp = `<div class="btn ${btnClass}">${item}</div>`
    btnTemp += temp
  })

  // 最終生成的HTML
  let html = `
    <div class="dialog-wrapper fadeIn">
      <div class="dialog${skinClass} ${animaArr[currAnimation][0]}">
        <div class="title">${title}</div>
        <div class="content">${content}</div>
        <div class="buttons">${btnTemp}</div>
      </div>
    </div>
  `;

  // 添加到Body
  document.body.innerHTML += html;
  // 獲取所需要的節點
  getNeedElement();
  // 綁定事件
  bindEvent(confirm, cancel, shadeClose);
  return elem;

}

第三步,編寫hide方法

// 最外層加類名hide
let hide = function () {

  // 最外層執行顯示動畫(固定)
  elem.classList.add('fadeOut');
  // 內容層執行關閉動畫
  dialog.classList.add(`${animaArr[currAnimation][1]}`);
  // 最終移除
  setTimeout(() => {
    elem.remove();
  }, 200);

}

第四步,編寫bindEvent方法

let bindEvent = function (confirm, cancel) {

 // confirm按鈕的回調
  confirmBtn && confirmBtn.addEventListener('click', e => {
    hide();
    confirm && confirm();
  })

  // cancel按鈕的回調
  cancelBtn && cancelBtn.addEventListener('click', e => {
    hide();
    cancel && cancel();
  })

  // 是否開啓點擊遮罩關閉
  if (shadeClose) {
    elem.addEventListener('click', e => {
      let target = e.target || e.srcElement;
      if (/dialog-wrapper/.test(target.className)) {
        hide();
      }
    })
  }

}

第五步,編寫getNeedElement方法

let getNeedElement = function () {
  
  // 一家人最重要是整整齊齊
  elem = document.querySelector('.dialog-wrapper');
  dialog = elem.querySelector('.dialog');
  cancelBtn = elem.querySelector('.cancel-btn');
  confirmBtn = elem.querySelector('.confirm-btn');

}

調用以及效果圖

  1. 無標題


dialog.show({
  content: '抱歉,該遊戲暫無Android版本'
})
  1. 自定義標題和按鈕


dialog.show({
  title: '版本更新',
  content: '檢測到最新版本爲V1.0.2,是否更新',
  btns: ['立即更新', '暫不更新']
})
  1. 動畫效果爲2時(彈性放大)


 dialog.show({
  title: '消息提示',
  content: '此操作將不可逆轉,確定刪除此項?',
  btns: ['確定', '怕了'],
  animation: 2
})

說明

自己可以擴展更多自定義參數,動畫需配合css3的animation

如果您喜歡這篇文章,那麼記得動動你們的,給個like或者關注我哦。

歡迎所有前端愛好者關注我的個人微信公衆號,我會經常分享最新,實用性高的前端文章以及技巧,祝你在前端開發的道路上刀過竹解!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章