模擬elementUI或使用自定義屬性簡單封裝對話框


前言

  現在前端框架有許多的UI框架可以選擇,但是樣式或者功能不一定是我們項目中想要的,因此很多時候需要自己封裝。此篇文件簡單介紹一下利用自定義標簽或者自定義擴展屬性來封裝UI組件,方便項目的其他地方復用,如果要封裝其他例如分頁功能、按鈕、動畫等等也是一樣的,這里主要講思路,大家完全可以舉一反三。

 

一、自定義標簽

  例如elmentUI的標簽都是el-開頭

  <el-dialog title="對話框">
    <span class="dialog-body">這是一段信息</span>
    <span class="dialog-footer">
      <el-button>取消</el-button>
      <el-button type="primary">確定</el-button>
    </span>
  </el-dialog>

  js去讀取並替換為瀏覽器可以識別解析的標簽(這里用jq寫會更方便,不過我懶得引入了):

let dialog = document.getElementsByTagName("el-dialog")[0];
dialog.outerHTML = `<div class="el-dialog">
<h3 class="dialog-header">${dialog.title}</h3>
<span class="dialog-body">${dialog.children[0].textContent}</span><span class="dialog-footer">
  <button class="el-button">${dialog.children[1].children[0].textContent}</button>
  <button class="el-button el-button-${dialog.children[1].children[1].attributes[0].value}">${dialog.children[1].children[1].textContent}</button>
</span></div>`;

  效果圖:

 

 

 

 二、自定義擴展屬性

  data-開頭,設置屬性值或內容,然后標簽替換

  <div class="el-dialog" data-title="自定義屬性對話框">
    <span class="dialog-body">這是一段信息</span>
    <span class="dialog-footer">
      <button class="el-button">取消</button>
      <button class="el-button el-button-primary">確定</button>
    </span>
  </div>

  js部分 元素.dataset.屬性 來讀取:

let dialog2 = document.getElementsByClassName("el-dialog")[1];
let h3 = document.createElement("h3");
h3.setAttribute("class","dialog-header");
h3.innerHTML = dialog2.dataset.title;
dialog2.insertBefore(h3,dialog2.children[0]);

  效果圖:

  

 

 

  樣式寫的比較簡單,dom元素操作也很單一,大家可以換jq操作會更加方便,這里主要講思路。

  項目源代碼:https://github.com/13632756286/user-defined


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM