HTML - <template> 標籤



HTML <template> 標籤是一種機制,用於儲存一些 HTML 或客戶端內容,在頁面載入時對使用者隱藏。瀏覽器在載入頁面時會評估 <template> 標籤的內容以確保其有效性;但是,內容不會顯示。除非使用 JavaScript 啟用,否則模板的內容不會顯示。

如果我們希望在 HTML 文件中多次使用相同的內容而無需任何更改,則可以使用 <template> 標籤。

<template> 標籤可以在 HTML 文件中的任何位置使用,例如在 <head>、<body>、<frameset> 或 <table> 元素中。

語法

<template>.....</template>

屬性

HTML 模板標籤支援 HTML 的全域性事件屬性。它還接受一個特定的屬性,如下所示。

HTML 模板標籤示例

以下示例將說明模板標籤的使用,何時、何地以及如何使用它來隱藏觸發點後面的元素。

使用模板標籤隱藏內容

當瀏覽器載入頁面時,我們可以隱藏模板標籤內的任何內容,並使用按鈕作為觸發點來稍後呈現該元素。在以下示例中,我們使用 <template> 標籤在頁面載入時儲存內容,稍後我們使用 JavaScript 顯示隱藏的內容。

<!DOCTYPE html>
<html>
<body>
   <h1>The template Element</h1>
   <p>
       When you click the button below, JavaScript is activated,
       and hidden content will become visible!
   </p>
   <button onclick="showContent()">Show hidden content</button>
   <template>
      <h2>Tutorialspoint</h2>
      <p>Tutorialspoint: 
        <q>
            is an EdTech organisation that provides courses 
            related to CSE and so many tutorials and DSA solutions.
        <q>
      </p>
      <p>Easy to learn!</p>
   </template>
   <script>
      function showContent() {
         let temp = document.getElementsByTagName("template")[0];
         let clon = temp.content.cloneNode(true);
         document.body.appendChild(clon);
      }
   </script>
</body>
</html>

使用模板標籤隱藏圖片

當瀏覽器載入頁面時,我們可以隱藏模板標籤內的任何內容,並使用按鈕作為觸發點來稍後呈現該元素。考慮以下示例,我們使用 <template> 標籤在頁面載入時隱藏圖片,稍後我們使用 JavaScript 顯示隱藏的內容。

<!DOCTYPE html>
<html>
<head>
   <title>HTML Template tag</title>
</head>
<body>
   <h2>Example of template tag</h2>
   <button onclick="clickMe()">Click Me</button>
   <br>
   <template id="mytemplate">
      <img src="https://tutorialspoint.tw/images/logo.png?v2" alt="logo">
      <script>
      alert("Thank you for choosing template. Click OK for tutorialspoint Logo.")
      </script>
   </template>
   <script>
      function clickMe() {
         var x = document.getElementsByTagName("template")[0];
         var clon = x.content.cloneNode(true);
         document.body.appendChild(clon);
      }
   </script>
</body>
</html>

支援的瀏覽器

標籤 Chrome Edge Firefox Safari Opera
template 是 26.0 是 13.0 是 22.0 是 8.0 是 15.0
html_tags_reference.htm
廣告

© . All rights reserved.