首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在滚动并单击时突出显示活动菜单项?

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

Stack Overflow用户
提问于 2014-11-23 02:34:26
回答 2查看 3K关注 0票数 1

我想在滚动并单击的当前菜单项中添加一个类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;
    });
EN

回答 2

Stack Overflow用户

发布于 2014-11-23 03:26:48

使用jQuery在click上添加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/

票数 2
EN

Stack Overflow用户

发布于 2014-11-23 03:24:56

<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....
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27080985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档