在另一个html(即模板)中打开一个html文件 [英] Open an html file inside another html(i.e. template)
问题描述
我有一个横幅HTML,其中包含一堆我想设置为模板的按钮(即首页,关于...等).在我的唯一页面(例如主页)上,我想导入"此模板html文件.我该如何编码?
I have a banner html with a bunch of buttons(i.e. home, about,..etc.) that I'd like to set as a template. On my unique pages(say the home page), I'd like to "import" this template html file. How do I code this?
我尝试了许多不同的方法并对其进行了查找,但我得到的最接近的结果是,当我导入时,它具有那些滚动条,并没有真正与页面集成"在一起.例如,我在寻找的一个很好的例子是arduino网站,顶部横幅没有变化.
I've tried many different ways and looked it up but the closest I got was that when I imported, it had those scrollers and wasn't really "integrated" with the page. A good example of what I'm looking for is for instance, the arduino website where the top banner doesn't change.
谢谢
推荐答案
您可以使用 HTML导入,以使用 <template>
元素,在其中添加要导入的元素.
You can use HTML Imports to import an external HTML file with a <template>
element where you add the elements you want to import.
在主文件中:
<head>
<link rel="import" href="template.html" id="myTemplate">
</head>
<body>
<div id="container"></div>
</body>
在template.html
文件中:
In the template.html
file:
<template>
<span>Hello World!</span>
</template>
<script>
//get the imported HTML document
var importedDoc = document.querySelector( '#myTemplate' ).import
//get the content of the template element
var content = importedDoc.querySelector( 'template' ).content
//add a compy to the main page
document.querySelector( '#container' ).appendChild( content.cloneNode( true ) )
</script>
在上面的示例中,<template>
元素的内容(<span>
文本"Hello World!"
)将被放置在主页的<div id=container>
元素中.
In the example above, the conent of the <template>
element (the <span>
text "Hello World!"
) will be put in the <div id=container>
element in the main page.
更新2019
Chrome 73之后将不再支持HTML导入.您应该使用上面列出的其他解决方案(polyfill,备用模块加载器,JS导入或直接通过fetch
下载).
HTML Imports won't be supported natively after Chrome 73. You should then use the other solutions listed above (the polyfill, an alternate module loader, JS import, or a direct download with fetch
).
这篇关于在另一个html(即模板)中打开一个html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!