HTML <template> tag
- Previous page <td>
- Next page <textarea>
Definitie en gebruik
<template>
tag wordt gebruikt als container om enkele HTML-inhoud te verbergen bij het laden van de pagina voor de gebruiker.
<template>
De inhoud ervan kan later met JavaScript worden weergegeven.
Als u有一些希望重复使用的 HTML 代码,但在需要时才显示出来,您可以使用 <template>
tag. Als er geen <template>
tag, moet u HTML-code maken met JavaScript om te voorkomen dat de browser deze weergeeft.
Voorbeeld
Voorbeeld 1
Gebruik <template>
Om enkele inhoud te behouden die bij het laden van de pagina wordt verborgen, en deze met JavaScript te tonen:
<button onclick="showContent()">Show hidden content</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>
Voorbeeld 2
为数组中的每一项使用一个新的 div 元素填充网页。每个 div 元素的 HTML 代码都在 template 元素中:
<template> <div class="myClass">I like: </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>
Example 3
Check the browser's support for <template>
Support:
<script> if (document.createElement("template").content) { document.write("Your browser supports template!"); } document.write("Your browser does not support template!"); } </script>
Global attributes
<template>
The tag also supports Global attributes in HTML.
Browser support
The numbers in the table indicate the first browser version to fully support this property.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
26.0 | 13.0 | 22.0 | 8.0 | 15.0 |
- Previous page <td>
- Next page <textarea>