HTML <template> 标签用于保存在页面加载时不会呈现的客户端内容,但可以在运行时使用 JavaScript 对其进行实例化。
模板的内容在没有使用 JavaScript 激活之前不会显示。浏览器在加载页面时会处理 <template> 元素的内容,以确保内容有效,但不会呈现内容。
当您想在 HTML 文档中多次使用相同的内容而不进行任何更改时,它也很有用。
<template> 标签可以放置在 <head>、<body>、<frameset> 或 <table> 元素内的任何位置。
<template> 标签是 HTML5 中新增的元素。
句法
<template>.........</template>
例子
<!DOCTYPE html>
<html>
<head>
<title>HTML Template tag</title>
<style>
body{
background-color: #e6e6fa;
}
</style>
</head>
<body>
<h2>Example of template tag</h2>
<button onclick="clickMe()">Click Me</button><br>
<template id="mytemplate">
<img src="bird.jpg" alt="bird's image" height="100" width="100">
<script>
alert("Thank you for choosing template. Click OK for image.")
</script>
</template>
<script>
function clickMe() {
var x = document.getElementsByTagName("template")[0];
var clon = x.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
</body>
</html>
输出:
属性:
标签特定属性:
<template> 标签不包含任何特定属性。
全局属性:
<template> 标签支持 HTML 中的全局属性。
支持浏览器
Element | Chrome |
IE | Firefox | Opera | Safari |
<template> | Yes | No | Yes | Yes | Yes |