首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jquery在单击导航项目和滚动浏览div时添加类

问使用jquery在单击导航项目和滚动浏览div时添加类
EN

Stack Overflow用户
提问于 2014-04-11 00:12:14
回答 2查看 680关注 0票数 0

我希望使用jquery添加一个类别的“选定”,无论是点击导航项目,以及滚动通过该部分的div。

到目前为止,我已经在点击导航项目时添加了类,但我不确定如何在滚动经过每个部分div时整齐地添加相同的效果。

以下是我的脚本,用于在单击时添加类(这非常简单和标准):

代码语言:javascript
复制
$('#fixednav li').click(function(){
$('#fixednav li').removeClass("selected");
$(this).addClass("selected");
});

当用户单击固定菜单中的项目时,...It all效果很好。但是,当用户在没有使用固定菜单的情况下向下滚动页面时,如何添加所选的类?每个部分都有一个div id,所以我认为可以很容易地添加一些东西,以便在滚动过div id时添加类。

Here's my fiddle

稍微向下滚动一点可以看到固定的导航弹出...

EN

回答 2

Stack Overflow用户

发布于 2014-04-11 00:18:14

我也遇到了同样的问题,我使用scrollspy解决了这个问题,下面是bootstrap上的链接和演示:

scrollspy

如果你有一些pb,请让我知道。

票数 0
EN

Stack Overflow用户

发布于 2014-04-11 00:24:02

检查这是否对fiddle有帮助

这是使用的js,检查html和css的小提琴。

代码语言:javascript
复制
var hei = $("#header").height();
    $(window).scroll(function(){
        if($(window).scrollTop() > hei){
            $("#header").addClass('fixed');
            $('.body-wrapper').css('margin-top',hei);
        }else{
            $("#header").removeClass('fixed');
            $('.body-wrapper').css('margin-top','0');
        }
    });
    $("#header li a").on('click', function(event){
        event.preventDefault();
        var header_height = $("#header").height();
        var target = $(this).attr('href');
        $('html, body').animate({
            scrollTop: $(target).offset().top-header_height
        }, 1000);
    });

    var aChildren = $("#header li").children(); // find the a children of the list items
    var aArray = []; // create the empty aArray
    for (var i=0; i < aChildren.length; i++) {    
        var aChild = aChildren[i];
        var ahref = $(aChild).attr('href');
        aArray.push(ahref);
    } // this for loop fills the aArray with attribute href values

    $(window).scroll(function(){
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();


        for (var i=0; i < aArray.length; i++) {
            var theID = aArray[i];
            var divPos = $(theID).offset().top-hei-30; // get the offset of the div from the top of page
            var divHeight = $(theID).height(); // get the height of the div in question
            if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
                $("a[href='" + theID + "']").addClass("nav-active");
            } else {
                $("a[href='" + theID + "']").removeClass("nav-active");
            }
        }

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

https://stackoverflow.com/questions/22993421

复制
相关文章

相似问题

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