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

Open an html file inside another html(i.e. template)

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

我尝试了很多不同的方法并进行了查找,但我得到的最接近的结果是,当我导入时,它有那些滚动条,而不是真正的 "integrated" 页面。我正在寻找的一个很好的例子是,例如,顶部横幅没有改变的 arduino 网站。

谢谢,

您可以在添加要导入的元素的地方使用 HTML Imports to import an external HTML file with a <template> 元素。

在主文件中:

<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 年更新

HTML Chrome 73 之后将不再支持导入fetch).