如何使用jQuery模拟多页面网站?

时间:2015-03-15 05:44:49

标签: javascript jquery html css

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

Here is the code I am currently working with on 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.

});

2 个答案:

答案 0 :(得分:0)

右转,你试图在这里重新发明轮子! :)

查看Jquery选项卡库:

http://jqueryui.com/tabs/

只需将代码复制到您的网站中, 删除样式表链接,然后离开! :D

答案 1 :(得分:0)

使用此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;  
}