實例
使用 <template> 標簽在頁面加載時該標簽中的內(nèi)容不會顯示,加載后可以使用 JavaScript 來顯示它:
<button onclick="showContent()">顯示隱藏內(nèi)容</button>
<template>
<h2>logo</h2>
<img decoding="async" src="https://atts.w3cschool.cn/attachments/image/20221207/1670380025475113.png" >
</template>
<script>
function showContent() {
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
嘗試一下 ?
瀏覽器支持
所有主流瀏覽器都支持 <template> 標簽。
標簽定義及使用說明
<template> 標簽定義在頁面加載時隱藏的一些內(nèi)容,該標簽中的內(nèi)容可以稍后使用 JavaScript 呈現(xiàn)。
如果您有一些需要重復使用的 HTML 代碼,則可以使用 <template> 設置為公用的模板。
更多實例
實例
實例中的每個數(shù)組元素都使用一個新的 div 元素來填充網(wǎng)頁。每個 div 元素的 HTML 代碼都在 template 元素內(nèi)::
<template>
<div class="myClass">我喜歡: </div>
</template>
<script>
var myArr = ["Google", "W3cschool", "Taobao", "Wiki", "Zhihu", "Baidu"];
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>
嘗試一下 ?
實例
查看瀏覽器是否支持 template 標簽:
if (document.createElement("template").content) {
document.write("您的瀏覽器支持 template 標簽!");
} else {
document.write("您的瀏覽器不支持 template 標簽!");
}
嘗試一下 ?
更多建議: