You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript将外部HTML文件内容加载到指定div中

院校网站导航点击替换内容功能实现

需求说明

正在练习制作一所院校的网站,页面body标签内共有三个元素,分别是<header>、内容容器、<footer>。另有一个about.html文件,其中仅包含HTML片段,无<body>和<head>标签,且已通过style.css为about.html的内容完成样式设置。需要实现的需求是:点击导航栏的About选项时,将当前页面的<div id="content"></div>内容替换为about.html中同名id的div内容。

注意:代码片段中提供的CSS暂未做响应式适配,计划完成本功能开发后再推进响应式改造工作。

现有content区域代码

<section id="home">
    <div class="main">
        <h1 class="slide">The Biggest</h1>
        <h1 class="slide">Educational</h1>
        <h1 class="slide">Network</h1>
        <h1 class="slide">Punjab Group</h1>
        <h1 class="slide">Of Colleges</h1>
        <h1 class="slide">Hafizabad</h1>
    </div>
    <div class="swipe">
        <img src="./PGC_Stock/chevron-down.svg" alt="swipe">
    </div>
</section>
<section id="team">
    <div class="card-container">
        <div class="cards" id="card-1">
            <img src="./PGC_Stock/ADMIN/khizar_abbas_sqr.jpg" alt="khizar_abbas">
            <div>
                <h1 class="name">Khizar Abbas</h1>
                <p class="status">IT Manager At PGC-Hafizabad</p>
            </div>
        </div>
        <div class="cards" id="card-2">
            <img src="./PGC_Stock/ADMIN/hafiz_fahad_sqr.jpg" alt="hafiz_fahad">
            <div>
                <h1 class="name">Hafiz Fahad</h1>
                <p class="status">Principal At PGC-Hafizabad</p>
            </div>
        </div>
        <div class="cards" id="card-3">
            <img src="./PGC_Stock/ADMIN/salman_butt.jpg" alt="salman_butt">
            <div>
                <h1 class="name">Salman Butt</h1>
                <p class="status">Vice Principal At PGC-Hafizabad</p>
            </div>
        </div>
        <div class="cards" id="card-5">
            <img src="./PGC_Stock/ADMIN/mian_afzal-scaled_sqr.jpg" alt="mian-afzal">
            <div>
                <h1 class="name">Sohail Afzal</h1>
                <p class="status">Executive Director PGC</p>
            </div>
        </div>
        <div class="cards" id="card-4">
            <img src="./PGC_Stock/ADMIN/mianamer_sqr.jpg" alt="mian-amer">
            <div>
                <h1 class="name">Mian Amer Mahmood</h1>
                <p class="status">Chairman PGC</p>
            </div>
        </div>
    </div>
</section>

现有核心基础代码

CSS代码

:root {
  --blue-color: #2c2b6f;
  --red-color: #e13a27;
  --red_2_color: #e13b28;
  --blue_2-color: #2c2b6d;
  --white-color: #ffffff;
  --font-light: GalanoGrotesque;
  --font-bold: GalanoGrotesque-Bold;
}

* {
  font-family: var(--font-light);
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  color: var(--white-color);
  background-color: var(--blue-color);
}


/* 导航栏样式 */
#navbar {
  position: relative;
  display: flex;
  width: 100%;
  height: 75px;
  align-items: center;
  justify-content: space-between;
  min-width: 100%;
}

#navbar::before {
  content: "";
  position: absolute;
  min-width: 100%;
  background-color: var(--red_2_color);
  z-index: -1;
  height: 100%;
}


/* Logo样式 */
.logo {
  margin-left: 10px;
  width: 120px;
}


/* 导航链接样式 */
#nav-links {
  display: flex;
  list-style: none;
}

#nav-links a {
  text-decoration: none;
  color: var(--white-color);
}

.nav-links {
  margin: 0 15px;
  font-size: 1.08rem;
  position: relative;
  cursor: pointer;
  text-transform: uppercase;
}


/* 社交链接样式 */
#social-links {
  margin-right: 10px;
}

.social-links {
  filter: invert();
  margin: 0 5px;
}

.social-links img {
  width: 25px;
  transition: all 300ms ease;
}

.social-links img:hover {
  transform: scale(1.5);
}

/* 导航栏样式结束 */

/* 默认内容区样式 */
#content {
  position: relative;
  margin-top: 10px;
  height: 100vh;
}

#content::before {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  background: url("../PGC_Stock/sldier-bg-gradient1.jpg") center center/cover
    no-repeat;
  z-index: -1;
}

#content {
  background-image: url(../PGC_Stock/slide-bg.png);
  background-size: 900px;
  background-repeat: no-repeat;
  background-position: bottom right;
}

#content div {
  position: absolute;
  left: 5%;
  top: 20%;
  display: flex;
  flex-direction: column;
}

#content span h1 {
  text-transform: uppercase;
  font-size: 4rem;
  line-height: 1;
}

.para {
  margin-top: 5px;
  font-size: 1.3rem;
}

.btn {
  margin-top: 5px;
  color: var(--blue-color);
  padding: 5px 5px;
  font-family: "Times New Roman", Times, serif;
  font-weight: 700;
  background-color: var(--white-color);
  border: none;
  border-radius: 5px;
  font-size: 1.5rem;
  width: 150px;
}

#footer {
  height: 60px;
  background-color: var(--red-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}

主页面HTML代码(已插入功能JS)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Punjab Group Of Colleges | Hafizabad</title>
  <link rel="stylesheet" href="./css/style.css">
</head>

<body>
  <header>
    <nav id="navbar">
      <div id="logo">
        <img class="logo" src="./PGC_Stock/LOGO/logo.svg" alt="logo">
      </div>
      <ul id="nav-links">
        <a>
          <li class="nav-links" onclick="about()">About</li>
        </a>
        <a>
          <li class="nav-links">Programmes</li>
        </a>
        <a>
          <li class="nav-links">Life At Campus</li>
        </a>
        <a>
          <li class="nav-links">Gallery</li>
        </a>
        <a>
          <li class="nav-links">Contact Us</li>
        </a>
      </ul>
      <div id="social-links">
        <a class="social-links" href="https://www.facebook.com/pgchfdofficial" target="_blank"><img src="./PGC_Stock/LOGO/facebook.png" alt="facebook"></a>
        <a class="social-links" href="https://www.instagram.com/pgchfd/" target="_blank"><img src="./PGC_Stock/LOGO/instagram.png" alt="instagram"></a>
        <a class="social-links" href="GATXUWWYDFFHN4SK64F6H3X6UVUCRGMR6BXJ4JAPT2MMG5QI5VRQLQNE" target="_blank"><img src="./PGC_Stock/LOGO/youtube.png" alt="youtube"></a>
      </div>
    </nav>
  </header>
  <section id="content">
    <div>
      <span>
                <h1 id="1">A Legacy Of</h1>
                <h1 id="2">Excellence</h1>
            </span>
      <span class="para">Pre 1st Year Admissions Open</span>
      <button class="btn" id="apply">Apply Now!</button>
    </div>
  </section>
  <footer id="footer">
    <p>Punjab Colleges Hafizabad</p>
    <p class="copy">&copy; 2021 Punjab Colleges. All Rights Reserved.</p>
    <div id="social-links">
      <a class="social-links" href="https://www.facebook.com/pgchfdofficial" target="_blank"><img src="./PGC_Stock/LOGO/facebook.png" alt="facebook"></a>
      <a class="social-links" href="https://www.instagram.com/pgchfd/" target="_blank"><img src="./PGC_Stock/LOGO/instagram.png" alt="instagram"></a>
      <a class="social-links" href="GATXUWWYDFFHN4SK64F6H3X6UVUCRGMR6BXJ4JAPT2MMG5QI5VRQLQNE" target="_blank"><img src="./PGC_Stock/LOGO/youtube.png" alt="youtube"></a>
    </div>
  </footer>
  <!-- 内容替换功能JS -->
  <script>
  function about() {
    const contentEl = document.getElementById('content');
    fetch('./about.html')
      .then(res => res.text())
      .then(html => {
        const temp = document.createElement('div');
        temp.innerHTML = html;
        const targetContent = temp.querySelector('#content');
        contentEl.innerHTML = targetContent ? targetContent.innerHTML : '<p>内容加载异常</p>';
      })
      .catch(err => {
        console.error(err);
        contentEl.innerHTML = '<p>内容加载失败,请稍后重试</p>';
      });
  }
  </script>
</body>

</html>

使用注意事项

  • 请确保about.html和主页面的相对路径和fetch中填写的路径一致,若about.html存放在根目录的page文件夹下,路径需改为./page/about.html
  • 本地直接打开HTML文件会触发浏览器跨域限制,建议使用本地开发服务器(如VS Code的Live Server插件)运行测试,部署到线上服务器后无此问题
  • about.html内必须包含id="content"的元素,否则会显示兜底提示

内容的提问来源于stack exchange,提问作者m-naeem66622

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:54:04