<template> | HTML模板标签的定义与用法
定义与用法
- <template>标签用于保存页面加载时不会呈现的客户端内容,可以在运行时使用JavaScript将其实例化。
- 如果没有JavaScript激活模板,则浏览器不会显示该模板的内容。
- 浏览器在加载页面时处理<template>元素的内容,以确保内容有效,但是不会呈现内容。
提示:当您想在HTML文档中多次使用相同内容而不进行任何更改时,它也很有用。
语法格式
<template>………</template>
示例代码
<button onclick="clickMe()">显示图片</button><br>
<div id="myimage"></div>
<template id="mytemplate">
<img src="/img/earth.jpg" alt="earth" height="200" width="300">
<script>
alert("谢谢选择图片模板,点击确定显示图片!")
</script>
</template>
<script>
function clickMe() {
var x= document.getElementsByTagName("template")[0];
var clon = x.content.cloneNode(true);
var myimage = document.getElementById('myimage');
myimage.appendChild(clon);}
</script>
效果展示
浏览器支持
IE | Firefox | Chrome | Safari | Opera |
---|---|---|---|---|
除IE外的主流浏览器都支持<template>标签。
全局属性
<template>标记支持HTML中的全局属性。