简体   繁体   English

导航链接在滚动位置上更改(单页站点)

[英]Navigation links change on scroll position (single page site)

I'm new to jQuery and javascript. 我是jQuery和javascript的新手。 I'm trying to create a single page website. 我正在尝试创建一个单页网站。 The navigation is fixed at the top. 导航固定在顶部。 When at a new 'part' of the single page I want the navigation to show that and the part currently on to be highlighted in the navigation. 在单个页面的新“部分”时,我希望导航显示该部分,并在导航中突出显示当前正在显示的部分。

I managed to somewhat do it with the scroll() but it only works if the variable 'top' is greater than 0. I know it is something probably really stupid I'm doing wrong but I'm new to this so I hope this doesn't bother you. 我设法用scroll()做到​​了这一点,但是只有在变量'top'大于0时它才起作用。我知道这可能是很愚蠢的,我做错了,但是我对此很陌生,所以我希望不会打扰你。

http://jsfiddle.net/mAPh6/ http://jsfiddle.net/mAPh6/

$(document).scroll( function() {
    var top = $(document).scrollTop();

    if ( 200 > top > 0 )
        $(".navLinkTop").css("border-bottom", "5px solid #fff568");
    else
        $(".navLinkTop").css("border-bottom", "none");

    if ( 400 > top > 200 )
        $(".navLinkAbout").css("border-bottom", "5px solid #fff568");
    else
        $(".navLinkAbout").css("border-bottom", "none");

    if ( 400 > top > 0 )
        $(".navLinkWork").css("border-bottom", "5px solid #fff568");
    else
        $(".navLinkWork").css("border-bottom", "none");

    if ( 400 > top > 0 )
        $(".navLinkContact").css("border-bottom", "5px solid #fff568");
    else
        $(".navLinkContact").css("border-bottom", "none");
});

When you do something like a > b > c it does not read out as "a is greater than b and b is greater than c". 当您执行类似a > b > c它不会读出为“ a大于b b大于c”。 Rather, what happens is the following: 相反,会发生以下情况:

  1. a > b > c evaluates to a > b > c计算为
  2. (true) > c (assuming a is indeed greater than b) which evaluates to (true) > c (假设a确实大于b),其结果为
  3. Number(true) > c since there is type conversion, which evaluates to Number(true) > c因为存在类型转换,其结果为
  4. 1 > c which is pretty random 1 > c这是相当随机的

So, 3 > 2 > 0 is true, but 3 > 2 > 1 is false. 因此, 3 > 2 > 0为真,但3 > 2 > 1为假。 Generally, you just need to use && when you're doing AND . 通常,您在执行AND时只需要使用&&

This is because the > operator is binary, that is it takes two arguments. 这是因为>运算符是二进制的,即它带有两个参数。

What you need to do is (a > b) && (b > c) , && means "and" 您需要做的是(a > b) && (b > c)&&表示“和”

In your case, this means changing statements like 200 > top > 0 to (top < 200) && (top > 0) 在您的情况下,这意味着将诸如200 > top > 0语句更改为(top < 200) && (top > 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM