如何使用jQuery实现导航栏 [英] How to implement nav bar using jQuery

查看:95
本文介绍了如何使用jQuery实现导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery实现导航栏导航。但没有运气!请查看这个小提琴

I am trying to implement nav bar navigation using jQuery. But no luck! Please have a look at this fiddle.

我的要求是根据滚动的内容激活菜单项,并根据单击的菜单项滚动内容。下面是代码

My requirement is to active menu item based on content scrolled, and scrolling the content based on menu item clicked. Below is the code

$('.menu-item').on('click', function () {
    var that = $(this);
    $('.menu-item').each(function () {
        $(this).removeClass('active');
    });
    that.addClass('active');
    var index = that.index();
    var target = $('.menu .menu-target').eq(index);
    $('.right').animate({
        scrollTop: target.offset().top
    }, 500);
});

$('.right').on('scroll', function () {
    var scrTop = $(this).scrollTop(),
        tgt = "";
    $('.menu-target').each(function () {
        var th = $(this),
            offTop = th.offset().top;
        if (offTop > scrTop && && tgt === "") {
            tgt = th;
        }
    });

    if (tgt !== "") {
        var index = tgt.index();
        $('.menu-item').each(function () {
            $(this).removeClass('active');
        });
        $('.menu-item').eq(index).addClass('active');
    }
});

但这不起作用。滚动时更新活动菜单项无效。如何解决这个问题?

But this is not working. Updating active menu item on scroll is not working. How to fix this?

编辑
试图解决问题,这里是代码 http://jsfiddle.net/SfR2c/11/
基于滚动内容更新菜单元素时出现一些不一致的情况!

Edit Tried to fix the issue and here is the code http://jsfiddle.net/SfR2c/11/ It is working with some inconsistency in updating menu element based on scroll content!

推荐答案

替换此

 var target = $('.menu .menu-target').eq(index);

由此

 var target = $('.right .menu-target').eq(index);

这篇关于如何使用jQuery实现导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆