HTML <template> 标签是一种机制,用于在页面加载时将某些 HTML 或客户端内容隐藏在用户面前。浏览器在加载页面时会评估 <template> 标签的内容,以确保其有效;但是,不会显示内容。除非模板未使用 JavaScript,否则不会显示模板的内容。
如果我们想在 HTML 文档中多次使用相同的内容而不进行任何更改,那么我们可以使用 <template> 标签。
语法
<template>.....</template>
属性
HTML 模板标签支持 HTML 的 全局属性 和 事件属性。
<template> 标签示例
下面的示例将说明<template> 标签的用法,何时、何地以及如何使用它来隐藏触发点后面的元素。
使用<template> 标签隐藏内容
当浏览器加载页面并使用按钮作为触发点来呈现该元素时,我们可以隐藏模板标签中的任何内容。在以下示例中,我们使用 <template> 标签在页面加载时保存内容,稍后我们将使用 JavaScript 显示隐藏内容。
<!DOCTYPE html>
<html>
<body>
<h1>The template Element</h1>
<p>
When you click the button below, JavaScript is activated,
and hidden content will become visible!
</p>
<button onclick="showContent()">Show hidden content</button>
<template>
<h2>Tutorialspoint</h2>
<p>Tutorialspoint:
<q>
is an EdTech organisation that provides courses
related to CSE and so many tutorials and DSA solutions.
<q>
</p>
<p>Easy to learn!</p>
</template>
<script>
function showContent() {
let temp = document.getElementsByTagName("template")[0];
let clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
</body>
</html>
使用<template> 标签隐藏图像
当浏览器加载页面并使用按钮作为触发点来呈现该元素时,我们可以隐藏模板标签中的任何内容。考虑以下示例,我们使用 <template> 标签在页面加载时隐藏图像,稍后我们将使用 JavaScript 显示隐藏的内容。
<!DOCTYPE html>
<html>
<head>
<title>HTML Template tag</title>
</head>
<body>
<h2>Example of template tag</h2>
<button onclick="clickMe()">Click Me</button>
<br>
<template id="mytemplate">
<img src="/images/logo.png?v2" alt="logo">
<script>
alert("Thank you for choosing template. Click OK for tutorialspoint Logo.")
</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> | 26.0 | 13.0 | 22.0 | 8.0 | 15.0 |