在html中創建自定義標簽


創建並使用自定義標簽

Web Components 標准非常重要的一個特性是,它使開發者能夠將HTML頁面的功能封裝為 custom elements(自定義標簽),本篇介紹使用 CustomElementRegistry 來管理我們的自定義標簽

1. 創建自定義標簽

  <script>
  class PopUpInfo extends HTMLElement {
    constructor () {
      super();
      // 在此定義自定義標簽 我頂一個icon和text並列的
      // Create a shadow root
      let shadow = this.attachShadow({mode: 'open'});
  // 創建我們需要的標簽
  let wrapper = document.createElement(&#39;div&#39;);
  let iconBox = document.createElement(&#39;div&#39;);
  let textBox = document.createElement(&#39;div&#39;);

  // 為標簽添加樣式
  wrapper.setAttribute(&#39;class&#39;,&#39;wapper&#39;);
  iconBox.setAttribute(&#39;class&#39;,&#39;icon&#39;);
  textBox.setAttribute(&#39;class&#39;,&#39;text&#39;);

  let text = this.getAttribute(&#39;text&#39;); // 獲取標簽里面傳遞的值
  textBox.textContent = text;

  let imgUrl;
  if(this.hasAttribute(&#39;img&#39;)) {
    imgUrl = this.getAttribute(&#39;img&#39;);
  } else {
    imgUrl = &#39;default.png&#39;; // 設置一個默認圖片
  }
  var img = document.createElement(&#39;img&#39;);
  img.src = imgUrl;
  iconBox.appendChild(img);

  // 書寫樣式
  var style = document.createElement(&#39;style&#39;);
  let lStyleStr = &#39;.wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}&#39;
  lStyleStr += &#39;.icon {margin-right: 10px; width: 50px; height: 50px;}&#39;
  lStyleStr += &#39;.icon img { width: 100%; height: 100%;}&#39;
  lStyleStr += &#39;.text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}&#39;
  style.textContent = lStyleStr;

  // 將樣式和dom元素掛載到頁面
  shadow.appendChild(style);
  shadow.appendChild(wrapper);
  wrapper.appendChild(icon);
  wrapper.appendChild(info);

}

}
</script>

2. 注冊自定義標簽

 

  <script> customElements.define('popup-info', PopUpInfo); </script>

3. 使用自定義標簽

<body>
  <popup-info img="you_picture.jpg" text="你的文字"></popup-info>
</body>


免責聲明!

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



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