我有以下内容,如果我单击带有 anchor #home
、#about
等的导航项,它会滚动到下一部分并设置导航元素类到 active
这很棒。
现在我在主页部分的内容中添加了一个“转到关于部分”按钮,该按钮具有 anchor #about
。它将我带到该部分,但将 actual button 设置为 active
类,而不是设置 nav item #about
到 active
。
我的评论在下面 - 只是想知道我该如何解决这个问题。谢谢!
$(function() {
var $sections = $('section.section');
$sections.each(function() {
var $section = $(this);
var hash = '#' + this.id;
$('a[href="' + hash + '"]').click(function(event) {
$scrollElement.stop().animate({
scrollLeft: $section.offset().left
}, 1200, 'easeOutCubic', function() {
window.location.hash = hash;
});
$('nav#main-nav a').removeClass('active');
if($(this).hasClass('content-menu-link')) {
var link = $(this).attr('href');
//Looks like it should be placed here after removing the
//active nav item and setting the var link to $(this),
//wondering how I can select the nav item whose anchor
//equals the var hash
$('a[href="' + hash + '"]').addClass('active');
} else {
$(this).addClass('active');
}
event.preventDefault();
});
});
});
fiddle 在这里:http://jsfiddle.net/8Zuzw/ .如您所见,如果您单击“主页”部分中的链接,它不会将导航“关于”更改为事件。它只是将链接设置为事件状态。如果您单击一个导航项,它会将其设置为事件状态,效果很好,现在只需添加一个功能即可,因此,如果您单击带有导航项 anchor 散列的导航外部链接,则应将导航项设置为active 不是链接类。
最佳答案
通过替换解决
$(this).addClass('active');
与
$('a[href="' + hash + '"]').addClass('active');
关于javascript - window.location.hash 将事件类放在当前 anchor 而不是导航 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543746/