原理:
使用jQuery
里面的 load() 方法。
// 语法
$(element).load(htmlfile)
示例
banner.html 的 body部分代码
<div style="width: 600px;height: 100px;margin:0 auto;background-color: hotpink;"></div>
index.html 的 body部分代码
<div class="header" style="width: 600px;height: 30px;margin:0 auto;background-color: yellow;"></div>
<div class="banner"></div>
<div class="footer" style="width: 600px;height: 50px;margin:0 auto;background-color: gray;"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function(){
$(".banner").load("./banner.html");
})
</script>
运行结果
详细内容——参考
https://blog.youkuaiyun.com/linyichao123/article/details/128285731
运行结果报错及原因
如果出现类似以下的错误提示:
Access to XMLHttpRequest at ‘file:///C:/Users/xxxx/Desktop/my/banner.html’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
原因:出现跨域安全性问题。
解决方法:
使用vscode的 live server 运行文件
详情请参考
https://blog.youkuaiyun.com/pink_cz/article/details/126896190