如何将不同的HTML部分显示为网站的不同页面

问题描述

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<div class="main-container">
    <!--NAVAGATION-->
    <ul class="nav">
    <li><a href="#home"></a>Home</li>
    <li><a href="#about"></a>About</li>
    <li><a href="#robotics">Robotics</a></li>
    <li><a href="#books">Books</a></li>
    </ul>
</div>

<div class="main-content">
    <section class="home section" id="home">
        <!--home page content-->
    </section>
    <section class="about section" id="about">
        <!--about page content-->
    </section>          
    <section class="robotics section" id="robotics">
         <!--robotics page content-->
    </section>
    <section class="books section" id="books">
         <!--books page content-->
    </section>
</div>
    
</div>

</body>
</html>

大家好!我正在使用此结构,并尝试将每个部分链接到其相应的NAV选项,以便仅显示所选内容(作为其他页面)。但是,对于本节中的“ id”属性和NAV选项的“ href”属性而言,它的作用不是太大,因为仅切换页面上的内容,而不切换页面本身。我已经尽力做到了,但这是我所能做到的。

解决方法

您可以使用CSS伪类:target来执行此操作。默认情况下,隐藏您的部分,当单击一个部分时,将该部分的显示更改为阻止:

section {
  display: none;
}

section:target {
  display: block;
}
<div class="main-container">
  <!--NAVAGATION-->
  <ul class="nav">
    <li><a href="#home">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#robotics">Robotics</a></li>
    <li><a href="#books">Books</a></li>
  </ul>
</div>

<div class="main-content">
  <section class="home section" id="home">
    home page content
  </section>
  <section class="about section" id="about">
    about page content
  </section>
  <section class="robotics section" id="robotics">
    robotics page content
  </section>
  <section class="books section" id="books">
    books page content
  </section>
</div>

</div>

,

<html>
<head>
<script>
function show(shown,hidden) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  return false;
}
</script>
</head>
<body>

  <div id="Page1" style="background-color:powderblue;">
    <h1>Hello I am In Section One Without Refresh </h1>
    <a href="#" onclick="return show('Page2','Page1');">Show page 2</a>
  </div>

  <div id="Page2" style="display:none;background-color:black;color:white;">
    
    <h1>Hello I am In Section Two Without Refresh </h1>
    <a href="#" onclick="return show('Page1','Page2');">Show page 1</a>
  </div>

</body>
</html>

看到您可以使用JavaScript像这样渲染您的部分,看起来就像是一个网页网站