一、html中的template标签
使用<template>
标签在页面加载时该标签中的内容不会显示。但是在后台查看页面DOM结构存在<template>
标签。这是因为template标签天生不可见,它设置了display:none;
属性。
<!--当前页面只显示"小猪佩奇"这个内容,不显示"我是template",这是因为template标签天生不可见-->
<template>
<div>
我是template
</div>
</template>
<h1>小猪佩奇</h1>
如果想要显示<template>
中的内容,可以加载后使用 JavaScript
来显示它。
<button onclick="showPig()">显示隐藏内容</button>
<template>
<h1>小猪佩奇</h1>
</template>
<script>
function showPig() {
var item = document.getElementsByTagName("template")[0]
var clon = item.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
如果有一些需要重复使用的 HTML 代码,也可以使用
<template>
设置为公用的模板。