HTML <template> 标签
HTML 内容模板(<template>)元素是一种用于保存客户端内容机制,该内容在加载页面时不会显示,但随后可以用Javascript 方法将其展示出来。将其视为一个可存储在文档中以便后续使用的内容。虽然解析器在加载页面时确实会读取<template>元素的内容,元素内容不会被渲染,只为后续使用。
实例
使用 <template> 保留页面加载时隐藏的内容。使用 JavaScript 来显示:
<!DOCTYPE html><html><body><h1>template 元素</h1><p>单击下面的按钮以显示模板元素中的隐藏内容。</p><button onclick="showContent()">显示隐藏内容</button><template><h2>Flower</h2><img src="/images/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></body></html>
定义和用法
<template> 标记用作容纳页面加载时对用户隐藏的 HTML 内容的容器。
<template> 中的内容可以使用 JavaScript 呈现。
如果您有一些需要重复使用的 HTML 代码,则可以使用 <template> 标记。如果在没有 <template> 标记的情况下执行此操作,必须使用 JavaScript 创建 HTML 代码,以防止浏览器显示这些代码。
浏览器支持
| 元素 | |||||
|---|---|---|---|---|---|
| <template> | 26.0 | 13.0 | 22.0 | 8.0 | 15.0 |
全局属性
<template> 标签同时支持 HTML 中的 全局属性。
更多实例
实例
对数组中的每个项,都使用一个新的 div 元素来填充网页。每个 div 元素的 HTML 代码都在 template 元素内:
<!DOCTYPE html><html><body><style>.myClass {color: white;background-color: DodgerBlue;padding: 20px;text-align: center;margin: 10px;}</style><h1>template 元素</h1><p>本例使用包含数组中每个项目的新 div 元素来填充网页。</p><p>每个 div 的 HTML 代码在 template 元素内。</p><p>单击下面的按钮,显示 template 元素中的隐藏内容。</p><button onclick="showContent()">显示隐藏的内容</button><template><div class="myClass">我喜欢:</div></template><script>var myArr = ["奥迪", "宝马", "奔驰", "大众", "捷豹", "沃尔沃"];function showContent() {var temp, item, a, i;temp = document.getElementsByTagName("template")[0];//get the div element from the template:item = temp.content.querySelector("div");//for each item in the array:for (i = 0; i < myArr.length; i++) {//Create a new node, based on the template:a = document.importNode(item, true);//Add data from the array:a.textContent += myArr[i];//append the new node wherever you like:document.body.appendChild(a);}}</script></body></html>
实例
检查浏览器是否支持 <template> 标签:
<!DOCTYPE html><html><body><h1>template 元素</h1><script>if (document.createElement("template").content) {document.write("您的浏览器支持 template!");} else {document.write("您的浏览器不支持 template!");}</script></body></html>