HTML <template> 標簽

定義和用法

<template> 標簽用作容器,用于在頁面加載時對用戶隱藏一些 HTML 內容。

<template> 內部的內容可以在稍后使用 JavaScript 呈現。

如果您有一些希望重復使用的 HTML 代碼,但在需要時才顯示出來,您可以使用 <template> 標簽。如果沒有 <template> 標簽,您需要使用 JavaScript 創建 HTML 代碼來防止瀏覽器呈現該代碼。

實例

例子 1

使用 <template> 來保存一些在頁面加載時將被隱藏的內容。并使用 JavaScript 顯示它:

<button onclick="showContent()">Show hidden content</button>
<template>
  <h2>Flower</h2>
  <img src="img_white_flower.jpg" width="214" height="204">
</template>
<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

親自試一試

例子 2

為數組中的每一項使用一個新的 div 元素填充網頁。每個 div 元素的 HTML 代碼都在 template 元素中:

<template>
  <div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
  var temp, item, a, i;
  temp = document.getElementsByTagName("template")[0];
  item = temp.content.querySelector("div");
  for (i = 0; i < myArr.length; i++) {
    a = document.importNode(item, true);
    a.textContent += myArr[i];
    document.body.appendChild(a);
  }
}
</script>

親自試一試

例子 3

檢查瀏覽器對 <template> 的支持:

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
} else {
  document.write("Your browser does not supports template!");
}
</script>

親自試一試

全局屬性

<template> 標簽還支持 HTML 中的全局屬性

瀏覽器支持

表中的數字注明了首個完全支持該屬性的瀏覽器版本。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
26.0 13.0 22.0 8.0 15.0