我正在尝试使用 jQuery 实现导航栏导航。但没有运气!请看this fiddle .
我的要求是根据滚动的内容激活菜单项,并根据单击的菜单项滚动内容。下面是代码
$('.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');
}
});
但这行不通。更新滚动上的事件菜单项不起作用。如何解决这个问题?
编辑 试图解决这个问题,这里是代码 http://jsfiddle.net/SfR2c/11/ 它在基于滚动内容更新菜单元素时存在一些不一致!
最佳答案
替换这个
var target = $('.menu .menu-target').eq(index);
由此
var target = $('.right .menu-target').eq(index);
关于javascript - 如何使用jQuery实现导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19315835/