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 |