我一直在阅读有关 <template>
的文档标签,我似乎无法理解它与简单地使用 <div>
有何不同那是 display: none;
文档:template tag
<template>
例子
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
对比
<div>
例子
<div id="productrow" style="display: none">
<tr>
<td class="record"></td>
<td></td>
</tr>
</div>
- 在底层,浏览器如何以不同方式处理这两个示例?
- 某些 JS 方法或 HTML 属性是否不同或不可用?
PS:我知道浏览器兼容性差异
最佳答案
考虑:
<template>
<style>
body: { background-color: black; }
</style>
<script>
alert('hello');
</script>
<audio src="alert.wav" autoplay></audio>
</template>
和:
<div style="display: none;">
<style>
body: { background-color: black; }
</style>
<script>
alert('hello');
</script>
<audio src="alert.wav" autoplay></audio>
</div>
当浏览器呈现它们时,它们的行为是否相同? (剧透:没有。)
不过,要解决您的具体问题:
- On a low level, how does the browser handle these 2 examples differently?
首先,<template>
中的 HTML不会成为 <template>
的子元素的 DOM 元素.它成为“惰性”DocumentFragment 的子项(间接地;这是一种简化),它们作为节点存在但不“做”任何事情,如上例所示。
除了“惰性”之外,模板内容没有“一致性要求”。你的<tr>
上面的例子是一个很好的例子。看看这里发生了什么:
const template = document.querySelector('template');
const div = document.querySelector('div');
console.log('template.innerHTML is', template.innerHTML);
console.log('div.innerHTML is', div.innerHTML);
<template>
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
<div style="display: none">
<tr>
<td class="record"></td>
<td></td>
</tr>
</div>
在普通文档中,<tr>
不能是 <div>
的 child ,所以浏览器只是将其删除。在 <template>
,该要求不存在。你会发现相同的,比如说,<div style="{{myStyle}}">
.在文档中,浏览器会丢弃 style
属性,因为它的值无效;在<template>
它不会。这就是 <template>
的原因对,嗯,模板很有用。
如果您想了解更多<template>
s 被渲染,我建议阅读 section about it in the HTML spec .阅读起来并不容易,部分内容可能难以理解,但您一定会学到很多东西。
- Are certain JS methods or HTML attributes different or not available?
<template>
元素有 content
属性,指向上面讨论的 DocumentFragment。
关于javascript - 浏览器如何处理 <template> 标签 VS <div> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50028946/