如何使用jquery来识别页面滚动到了哪个部分

How can I use jquery to recognize which section the page has scrolled to?

本文关键字:个部 滚动 jquery 何使用 识别      更新时间:2023-09-26

我有一个页面是这样的:

<nav style="position:fixed;top=0;left=0;width:100px;">
  <a class="one" href="#one">One</a>
  <a class="two" href="#two">Two</a>
  <a class="three" href="#three">Three</a>
  <a class="four" href="#four">Four</a>
  <a class="five" href="#Five">Five</a>
</nav>
<section style="margin-left:120px;height:550px;">
  <a name="one" id="one"></a>
  Content of section one ...
</section>
<section style="margin-left:120px;height:350px;">
  <a name="two" id="two"></a>
  Content of section two ...
</section>
<section style="margin-left:120px;height:750px;">
  <a name="three" id="three"></a>
  Content of section three ...
</section>
<section style="margin-left:120px;height:450px;">
  <a name="four" id="four"></a>
  Content of section four ...
</section>
<section style="margin-left:120px;height:250px;">
  <a name="five" id="five"></a>
  Content of section five ...
</section>

导航总是可见的,当用户单击链接时,它将在jquery中获得.active类。但是当用户滚动到一个页面时,我想根据可见窗口顶部的部分来更改.active链接
我试着玩$(window).scroll()和$(link.hash).offset().top,但老实说,我不知道如何管理它才能正常工作。

您可以使用jquery的:visible选择器,参见此示例;

$("section:visible").filter(":last-child").addClass("active");

漂亮的插件做到了这一点:http://imakewebthings.github.com/jquery-waypoints/