在另一个html(即模板)中打开一个html文件

问题描述 投票:0回答:1

我有一个带有一堆按钮(即主页、关于等)的横幅 html,我想将其设置为模板。在我独特的页面(比如主页)上,我想“导入”这个模板 html 文件。我该如何编码?

我尝试了很多不同的方法并进行了查找,但我得到的最接近的是,当我导入时,它有那些滚动条,并且并没有真正与页面“集成”。我正在寻找的一个很好的例子是 arduino 网站,其中顶部横幅不会改变。

谢谢,

html templates html-imports html5-template
1个回答
3
投票

您可以使用 HTML Imports 导入带有

<template>
元素的外部 HTML 文件,您可以在其中添加要导入的元素。

在主文件中:

<head>
   <link rel="import" href="template.html" id="myTemplate">
</head>
<body>  
   <div id="container"></div>
</body>

template.html
文件中:

<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>
元素中。

2019年更新

Chrome 73 之后将不再原生支持 HTML 导入。然后您应该使用上面列出的其他解决方案(polyfill、备用模块加载器、JS 导入或使用

fetch
直接下载)。

© www.soinside.com 2019 - 2024. All rights reserved.