我有一个横幅HTML,其中包含一堆我想设置为模板的按钮(例如,home,about..etc。)。在我的唯一页面(例如主页)上,我想“导入”此模板html文件。我该如何编码?
我尝试了许多不同的方法并进行了查找,但是最接近的是,当我导入时,它具有那些滚动条,并且并未真正与页面“集成”在一起。我正在寻找的一个很好的例子是,例如arduino网站,顶部横幅没有变化。
谢谢,
您可以使用HTML导入来导入带有<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
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句