javascript - HTML 模板元素 : Clarification

标签 javascript html templates html5-template

我最近发现了 HTML template元素,并希望得到一些澄清。

据我所知,这三个显着特征是:

  • template不在屏幕上呈现
  • template不会进入 DOM
  • 还有一个 contenttemplate 之间充当虚拟元素的属性及其内容

除此之外,一个<template>可能是 div , 从屏幕和 DOM 中隐藏。在这方面,JavaScript 用来利用 template就像尝试使用 div 伪造一个一样.

问题是,这是正确的吗?我问是因为:

  • 我只需要在自己的脑海里弄清楚
  • 为不支持的浏览器伪造一个相对容易。

谢谢

最佳答案

有一些主要区别:

  1. 脚本 ( <script> ) 在 <template> 中元素不会立即执行

  2. 模板内的媒体内容( <audio><video><img> )不会立即加载

    相反,它们将在渲染的 DOM 树中插入后执行或加载。

  3. querySelector()方法调用和 CSS 选择器不会探索 <template> 的内容, 但您仍然可以使用 querySelector() 访问其中的元素在其 content属性(property)。

  4. 使用 HTML5 模板,您可以访问 Document Fragment 形式的所有内容,并使用 appendChild() 将其插入到 DOM 树中,而不是修改 innerHTML .

  5. <template>元素可以放在 <head> 中元素。

  6. 您可以使用 .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/

相关文章:

javascript - 如何使溢出-y : hidden; work on click with jquery?

javascript - 窗口高度为 100% 的响应式设计,当父 div 内容大于定义的高度时推送兄弟 div

javascript - 如何动态加载CSS文件

c++ - 由于数据类型在运行时变化而停留在设计上

c++ - 使用 C++ 可变参数模板,如何存储一组异构类型的对象并迭代它们?

C++11 : Compare lambda expression

javascript - 使用 .filter 过滤对象数组

javascript - D3 .bandwidth() 返回 NaN

php - 如何从我的数据库中选择一个值并与其他值匹配

javascript - 如何自动循环显示图像数组?