简体   繁体   中英

Change CSS of Anchor Tag once a page has been selected - single page website

I have a single page website split into 5 pages (sections), each section fills the screen and when a user clicks on the nav it smoothly scrolls down to that section.

I cant figure out how to underline the anchor element in the upper nav once that page has been selected. I just want it to alert the user which page they are on and I would also need it to change even if the user uses the scroll bar to navigate to that section.

Each section of the page has an id which is linked from the nav. I know how to do this if each section was its own page but not when its a single page site.

Is there a jquery plugin or pure CSS way of doing this please?

jQuery would be your best bet on that one. This will automatically change the nav element when the user scrolls through the page. This works best if each section has the same height, but can be changed a bit to work with multiple section heights. Might need a little changing to fit into your site exactly.

//activates every time user scrolls
$(window).scroll(function () {

    //gets the current scroll height
    scroll = $(document).scrollTop()

    //gets section height -- this is where the editing will have to be done if
    //each section is a different height
    H = $('.section_class_name').height()

    //get the number of sections down
    place = (scroll) / H;
    place = Math.floor(place) - 1;

    if($(document).scrollTop() >= H) {
        //all other nav items have no background
        $('#menu_ul li').css('background', '');

        //the corresponding nav element has this background
        $('#menu_ul li').eq(place).css({'background':'#505080','border-radius':'9px'});
    }
})

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