如何使用jQuery模拟多页面站点

How do I simulate a multi page site using jQuery?

本文关键字:站点 模拟 何使用 jQuery      更新时间:2023-09-26

我正在处理的网站是一个单页网站,但我想使用 css/jQuery 模拟一个多页网站,以便在导航中单击正确的链接时隐藏/显示网站的不同部分。

这是我目前正在JSFiddle上使用的代码。

.HTML

<header id="top">
 <nav>
  <ul>
   <li> 
    <a href="#about">About</a>
   </li>
   <li>
    <a href="#skills">Skills</a>
   </li>
   <li>
    <a href="#projects">Projects</a>
   </li>
   <li>
    <a href="#contact">Contact</a>
   </li>
  </ul>
 </nav>
</header>
<main role="main" id="main">
 <section id="about">
 </section>
 <section id="skills">
 </section>
 <section id="projects">
 </section>
 <section id="contact">
 </section>
</main>

.CSS

.active {
  background: $lightest-blue;
  color: $blue;
}
.hide-section {
  display: none;
}
section {
  height: 1em;
  background: blue;
}

JavaScript

// Create Variables pointing to all Nav links and the About section link.
var siteNav = $("#top li").children();
var aboutLink = siteNav[0];
// Create Variables poingting to all Sections and the About section.
var siteSections = $("#main").children();
var aboutSection = siteSections[0];
// Hide all major sections by adding CSS class.
siteSections.addClass("hide-section");
// Upon document being ready, make user "arrive" at the About section by removing the hide class on it.
// Add active class to About section link.
$(function() {
  $(aboutLink).addClass("active");
  $(aboutSection).removeClass("hide-section");
});
// 1. Capture click on Nav anchor.
$("#top a").click(function() {
  // 1.1 Remove active class from all links.
  siteNav.removeClass("active");
  // 1.2 Add active class to clicked link.
  $(this).addClass("active");
  // 1.3 Identify proper section.
  var hrefLink = $(this).attr("href");
  // 1.4 Hide all other sections.
  siteSections.addClass("hide-section");
  // 1.5 Reveal proper section.
});

等一下,你正试图在这里重新发明轮子! :)

看看 Jquery 选项卡库:

http://jqueryui.com/tabs/

只需将代码复制到您的网站,删除样式表链接,然后就可以了!:D

使用此 JavaScript 在屏幕之间切换。我添加了一些css,以便您可以看到不同的部分来来去去。

$("#top a").click(function() {
 // 1.1 Remove active class from all links.
 siteNav.removeClass("active");
 // 1.2 Add active class to clicked link.
 $(this).addClass("active");
 // 1.3 Identify proper section.
 var hrefLink = $(this).attr("href");
 // 1.4 Hide all other sections.
 $('#'+siteSections[0].id).hide();
 $('#'+siteSections[1].id).hide();
 $('#'+siteSections[2].id).hide();
 $('#'+siteSections[3].id).hide(); 
 // 1.5 Reveal proper section.
 $(hrefLink).show();
});

和一些 CSS

section{
background:red;
}
#about{
 background-color:blue;  
}
#skills{
 background-color:yellow;  
}