jQuery在向下滚动页面时更改哈希(片段标识符) [英] jQuery change hash (fragment identifier) while scrolling down page

查看:70
本文介绍了jQuery在向下滚动页面时更改哈希(片段标识符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个寻呼机网站。例如。每个页面(总共5个)位于一个大页面上,主菜单固定在顶部。当您单击菜单链接时,它会将您向下滑动到该页面锚标记,并且单击的菜单项将获得活动CSS类。

I'm building a one pager website. Eg. every page (5 in total) is on one big page with the main menu fixed at the top. When you click on a menu link it slides you down to that pages anchor tag and the clicked menu item get a "active" CSS class.

我现在要做的是允许用户滚动自己,但仍然有菜单活动项和URL散列更改。

What I'd like to do now is allow the user to scroll themself but still have the menu "active" item and URL hash change as they do.

所以我的问题基本上是如何知道用户何时向下滚动到另一个页面,以便我可以更新菜单和URL哈希(片段标识符)。

So my question basically is how do I know when the user has scrolled down to a different page so I can update the menu and URL hash (fragment identifier).

谢谢

推荐答案

它可能但你的页面有要求(我的解决方案)工作):

its possible but there are a requirement to your page (for my solution to work):

您的页面必须以div(或任何部分)与唯一ID分开(我希望您不要使用anchor < a> 's)

your page have to be separated in divs(or sections whatever) with unique ids (i hope you dont use anchor <a>'s)

比你可以使用这样的代码:

than you can use code like this:

$(document).bind('scroll',function(e){
    $('section').each(function(){
        if (
           $(this).offset().top < window.pageYOffset + 10
//begins before top
        && $(this).offset().top + $(this).height() > window.pageYOffset + 10
//but ends in visible area
//+ 10 allows you to change hash before it hits the top border
        ) {
            window.location.hash = $(this).attr('id');
        }
    });
});

这样的html

<section id="home">
  Home
</section>
<section id="works">
  Works
</section>
<section id="about">
  About
</section>

这篇关于jQuery在向下滚动页面时更改哈希(片段标识符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆