HTML教程-HTML<template>标签

HTML <template>
标签用于保存在页面加载时不会呈现的客户端内容,但可以在运行时使用 JavaScript 实例化。
模板的内容在未通过 JavaScript 激活之前不会显示。浏览器在加载页面时会处理 <template>
元素的内容,以确保内容是有效的,但不会呈现内容。
在不带任何更改的情况下,在 HTML 文档中多次使用相同的内容时,<template>
标签也非常有用。
<template>
标签可以放置在 <head>
、<body>
、<frameset>
或 <table>
元素的任何位置。
<template>
标签是 HTML5 中新增的元素。
语法
<template>...</template>
以下是关于 HTML <template>
标签的一些规范:
显示 | 无 |
---|---|
开始标签/结束标签 | 开始标签和结束标签都有 |
用法 | 格式化 |
示例
<!DOCTYPE html>
<html>
<head>
<title>HTML Template 标签</title>
<style>
body {
background-color: #e6e6fa;
}
</style>
</head>
<body>
<h2>template 标签示例</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 中的全局属性。
支持的浏览器
元素 | ![]() | ![]() | ![]() | ![]() | ![]() |
---|---|---|---|---|---|
<template> | 是 | 否 | 是 | 是 | 是 |