前端学习-01 HTML引入公共头部和底部

2019-06-19  本文已影响0人  落雁城主

在一些官网通常需要引入公共头部和底部, 同时设置头部相应导航栏的高亮显示
解决方法: 通过jQuery的load方法引入公共部分结构(不需要完整的HTML结构, 只放头部和底部的内容)
1.header.html文件

<!-- 公共头部 -->
<div class="head">
    <h2>公共头部</h2>
    <ul class="head-content">
        <li>公共头部-01</li>
        <li>公共头部-02</li>
        <li>公共头部-03</li>
    </ul>
</div>

2.footer.html

<!-- 公共底部 -->
<div class="head">
    <h2>公共底部</h2>
    <div>底部内容</div>
</div>
  1. 整合文件index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>html引入公共文件</title>
</head>
<body>
    <!-- 引入公共头部 -->
    <div class="header"></div>
    <!-- HTML内容 -->
    <div class="content">
        <h1>HTML内容</h1>
    </div>
    <!-- 引入公共底部 -->
    <div class="footer"></div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    $(function() {
        // 导入头部和底部
        $('.header').load('./header.html', function() {
            // 加载完成后设置高亮部分
            $('.head-content li:first-child').css('color', 'red');
        });
        $('.footer').load('./footer.html');
    })
</script>
</html>
  1. 注意:
    Jquery的load()一般是加载服务器上的文件(非本地文件),这个概念需要弄清楚。要发布网站后通过http协议进行访问,本地file协议浏览会产生跨域问题。

5.效果图


image.png

参考文章

-https://blog.csdn.net/qq_38860424/article/details/80269421

前端小白学习之旅

上一篇 下一篇

猜你喜欢

热点阅读