HTML內(nèi)容模板( <template>)元素是一種用于保存客戶端內(nèi)容機(jī)制,該內(nèi)容在加載頁(yè)面時(shí)不會(huì)呈現(xiàn),但隨后可以(原文為 may be)在運(yùn)行時(shí)使用JavaScript實(shí)例化。 將模板視為一個(gè)可存儲(chǔ)在文檔中以便后續(xù)使用的內(nèi)容片段。雖然解析器在加載頁(yè)面時(shí)確實(shí)會(huì)處理 <template>元素的內(nèi)容,但這樣做只是為了確保這些內(nèi)容有效;但元素內(nèi)容不會(huì)被渲染。
示范如何使用template標(biāo)簽:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>HTML template標(biāo)簽的使用(菜鳥教程 (cainiaoplus.com))</title> </head> <body> <p>Content inside a template tag is hidden from the client.</p> <template> <h2>Views</h2> <img src="views.png"> </template> <p>A later example will show you how to use JavaScript to display the template content.</p> </body> </html>測(cè)試看看 ?/?
IEFirefoxOperaChromeSafari
所有主流瀏覽器都支持 <template> 標(biāo)簽。
<template>標(biāo)記將其內(nèi)容從客戶端隱藏起來(lái)。
<template>標(biāo)記內(nèi)的內(nèi)容將不會(huì)呈現(xiàn)。
以后可以使用JavaScript使內(nèi)容可見并呈現(xiàn)。
當(dāng)您有要一遍又一遍地使用HTML代碼時(shí),請(qǐng)使用<template>標(biāo)記,但是直到您要使用它時(shí)才使用。要在沒有 <template>標(biāo)記的情況下執(zhí)行此操作,必須使用JavaScript創(chuàng)建HTML代碼,以防止瀏覽器呈現(xiàn)代碼。
<!DOCTYPE html> <html> <body> <h1>HTML template標(biāo)簽的使用(菜鳥教程 (cainiaoplus.com))</h1> <p>Click the button to get the content from a template, and display it in the web page.</p> <button onclick="showContent()">Show content</button> <template> <h2>views</h2> <img src="views.png" width="300" height="204"> </template> <script> function showContent() { var temp = document.getElementsByTagName("template")[0]; var clon = temp.content.cloneNode(true); document.body.appendChild(clon); } </script> </body> </html>測(cè)試看看 ?/?
<template>標(biāo)簽是HTML5中的新標(biāo)簽。
<template> 標(biāo)簽支持 HTML 的全局屬性。
<template> 標(biāo)簽支持 HTML 的事件屬性。