我最近发现了 HTML template
元素,并希望得到一些澄清。
据我所知,这三个显着特征是:
-
template
不在屏幕上呈现 -
template
不会进入 DOM - 还有一个
content
在template
之间充当虚拟元素的属性及其内容
除此之外,一个<template>
可能是 div
, 从屏幕和 DOM 中隐藏。在这方面,JavaScript 用来利用 template
就像尝试使用 div
伪造一个一样.
问题是,这是正确的吗?我问是因为:
- 我只需要在自己的脑海里弄清楚
- 为不支持的浏览器伪造一个相对容易。
谢谢
最佳答案
有一些主要区别:
脚本 (
<script>
) 在<template>
中元素不会立即执行。模板内的媒体内容(
<audio>
、<video>
、<img>
)不会立即加载。相反,它们将在渲染的 DOM 树中插入后执行或加载。
querySelector()
方法调用和 CSS 选择器不会探索<template>
的内容, 但您仍然可以使用querySelector()
访问其中的元素在其content
属性(property)。使用 HTML5 模板,您可以访问 Document Fragment 形式的所有内容,并使用
appendChild()
将其插入到 DOM 树中,而不是修改innerHTML
.<template>
元素可以放在<head>
中元素。您可以使用
.innerHTML
以字符串形式访问模板内容或作为 DocumentFragment 使用.content
.
要伪造所有这些行为是相当困难的。有some polyfills可以部分做到这一点。我推荐 Neovov's one .
看看这个说明性的例子:
//explore the content of the template
var script = T1.content.querySelector( 'script' )
console.log( script.innerHTML )
function insert() {
//insert the real templete
Target1.appendChild( T1.content.cloneNode( true ) )
//insert the fake template
Target2.innerHTML += D1.innerHTML
}
<template id=T1>
Real Template -
<script>console.log( 'executed at each insertion' )</script>
</template>
<div hidden id=D1>
Fake Template -
<script>console.log( 'executed only at parsing' )</script>
</div>
<button onclick="insert()">insert</button>
<div id=Target1><div>
<div id=Target2><div>
关于javascript - HTML 模板元素 : Clarification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065668/