如何在滚动时突出显示活动菜单项并单击?

时间:2014-11-22 18:34:26

标签: javascript jquery css

我想在滚动时向当前菜单项添加一个类active,然后单击。这是一个包含不同部分的单个(长)页面。单击某个项目时,活动状态应切换到当前状态。

我提出了以下代码,但现在我不能整合上述代码:

// Click event
    $('#primary-navwrapper li a[href^="#"]').click(function(event) {

        // Prevent from default action to intitiate
        event.preventDefault();

        // The id of the section we want to go to
        var anchorId = $(this).attr('href');

        // Our scroll target : the top position of the section that has the id referenced by our href
        var target = $(anchorId).offset().top - offset;
        console.log(target);

        $('html, body').stop().animate({ scrollTop: target }, 500, function () {
            window.location.hash = anchorId;
        });

        return false;
    });

2 个答案:

答案 0 :(得分:2)

使用jQuery在active上添加click类很简单。您只需在点击处理程序中使用此代码

//remove active from all anchor and add it to the clicked anchor
        $('#primary-navwrapper li a[href^="#"]').removeClass("active")
        $(this).addClass('active');

对于滚动部分,您需要监控滚动条的位置,并将其与每个页面偏移进行比较,如此

//check the pages when scroll event occurs
$(window).scroll(function(){
    // Get the current vertical position of the scroll bar
    position = $(this).scrollTop();
    $('#primary-navwrapper li a[href^="#"]').each(function(){
          var anchorId = $(this).attr('href'); 
           var target = $(anchorId).offset().top - offset;
           // check if the document has crossed the page
        console.log(position,target);
        if(position>=target){
             //remove active from all anchor and add it to the clicked anchor
            $('#primary-navwrapper li a[href^="#"]').removeClass("active")
            $(this).addClass('active'); 
        }
    })

以下是演示http://jsfiddle.net/k5afwfva/

答案 1 :(得分:0)

<nav>
    <a href="#" class="item">item</a>
    <a href="#" class="item">item</a>
    <a href="#" class="item">item</a>
    <a href="#" class="item">item</a>
</nav>


var el = $(".item"),
    yPos = 0;


el.click(function(event){
    event.preventDefault();

    $(this).addClass("active").siblings().removeClass("active");
});
$(window).scroll(function(){

    yPos = $(this).scrollTop();

    //i'm almost sure that you will need to calculate offset of your section to know when to switch classes

    if(yPos > 100){
        el.removeClass("active").eq(1).addClass("active");
    }
    if(yPos > 200){
        el.removeClass("active").eq(2).addClass("active");
    }
    //etc....
});