技术文档

HTML <template> 标签

更新时间:2025-03-13 浏览量:

实例

使用<template>保留页面加载时隐藏的内容。使用JavaScript来显示:

<button onclick="showContent()">显示被隐藏的内容</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>

定义和用法  

<template>标记用作容纳页面加载时对用户隐藏的HTML内容的容器。  

<template>中的内容可以稍后使用JavaScript呈现。  

如果您有一些需要重复使用的HTML代码,则可以使用<template>标记。如果在没有<template>标记的情况下执行此操作,必须使用JavaScript创建HTML代码,以防止浏览器呈现这些代码。  

全局属性  

<template>标签同时支持HTML中的全局属性。  

实例  

对数组中的每个项,都使用一个新的div元素来填充网页。每个div元素的HTML代码都在template元素内:

<template>

<div class="myClass">我喜欢:</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>

实例  

检查<template>的浏览器支持:

<script>

if (document.createElement("template").content) {

document.write("Your browser supports template!");

} else {

document.write("您的浏览器不支持 template!");

}

</script>