简体   繁体   中英

Navigation links change on scroll position (single page site)

I'm new to jQuery and 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.

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". Rather, what happens is the following:

  1. a > b > c evaluates to
  2. (true) > c (assuming a is indeed greater than b) which evaluates to
  3. Number(true) > c since there is type conversion, which evaluates to
  4. 1 > c which is pretty random

So, 3 > 2 > 0 is true, but 3 > 2 > 1 is false. Generally, you just need to use && when you're doing 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"

In your case, this means changing statements like 200 > top > 0 to (top < 200) && (top > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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