当前位置:首页 > HTML5教程 > HTML5技巧

HTML <template> 标签

html <template> 标签

  • <td>

实例

使用 <template> 保留页面加载时隐藏的内容。使用 javascript 来显示:

<button onclick="showcontent()">显示被隐藏的内容</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>

亲自试一试

页面下方有更多 tiy 实例。

定义和用法

<template> 标记用作容纳页面加载时对用户隐藏的 html 内容的容器。

<template> 中的内容可以稍后使用 javascript 呈现。

如果您有一些需要重复使用的 html 代码,则可以使用 <template> 标记。如果在没有 <template> 标记的情况下执行此操作,必须使用 javascript 创建 html 代码,以防止浏览器呈现这些代码。

浏览器支持

元素 chrome ie firefox safari opera
<template> 26.0 13.0 22.0 8.0 15.0

全局属性

<template> 标签同时支持 html 中的全局属性。

更多实例

实例

对数组中的每个项,都使用一个新的 div 元素来填充网页。每个 div 元素的 html 代码都在 template 元素内:

<template>
  <div class="myclass">我喜欢:</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>

亲自试一试

实例

检查 <template> 的浏览器支持:

<script>
if (document.createelement("template").content) {
  document.write("your browser supports template!");
} else {
  document.write("您的浏览器不支持 template!");
}
</script>

亲自试一试

  • <td>

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!