當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML template用法及代碼示例

HTML中的<template>標記用於存儲HTML代碼片段,可以將其克隆並插入HTML文檔中。標簽的內容對存儲在客戶端的客戶端是隱藏的。插入直到使用JavaScript激活為止。使用JavaScript從模板獲取內容,並將其添加到網頁。

用法:

<template> Contents... </template>

注意:<template>標記是HTML 5中的新增標記。

範例1:本示例使用模板標簽,並且將內容隱藏在模板標簽中。

<!DOCTYPE html> 
<html> 
      
<head>  
    <title>  
        HTML template tag  
    </title>  
</head>  
  
<body> 
    <h1>GeeksforGeeks</h1> 
          
    <h3>HTML template tag</h3> 
  
    <p> 
        Content inside a template tag is 
        hidden from the client. 
    </p> 
  
    <template> 
        <h2> 
            GeeksforGeeks:A computer science portal 
        </h2> 
      
        <img src= 
"https://contribute.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png"> 
      
        Content Writer:<input type="text" placeholder="author name"> 
    </template> 
  
    <p>End of the example of template tag</p> 
</body> 
  
</html>                    

輸出:
template1



範例2:本示例使用JavaScript顯示模板標簽內容。

<!DOCTYPE html> 
<html> 
  
<head>  
    <title>  
        HTML template tag  
    </title>  
</head>  
  
<body> 
    <h1>GeeksforGeeks</h1> 
              
    <h3>HTML template tag</h3> 
      
    <p> 
        Click the button to get the content from 
        a template, and display it in the web page. 
    </p> 
      
    <button onclick="myGeeks()"> 
        Show content 
    </button> 
      
    <template> 
        <h2> 
            GeeksforGeeks:A computer science portal 
        </h2> 
      
        <img src= 
"https://contribute.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png"> 
          
        <br> 
          
        Content Writer:<input type="text" placeholder="author name"> 
    </template> 
      
    <!-- Script to display the content of template tag -->
    <script> 
        function myGeeks() { 
            var t = document.getElementsByTagName("template")[0]; 
            var clone = t.content.cloneNode(true); 
            document.body.appendChild(clone); 
        } 
    </script> 
</body> 
  
</html>                    

輸出:
單擊按鈕之前:
template2
單擊按鈕後:
template tag

支持的瀏覽器:<template>標簽支持的瀏覽器如下:

  • 穀歌瀏覽器26.0
  • Internet Explorer 13.0
  • Firefox 22.0
  • Safari 9.0
  • Opera 15.0




相關用法


注:本文由純淨天空篩選整理自sanjoy_62大神的英文原創作品 HTML | template Tag。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。