javascript - window.location.hash 将事件类放在当前 anchor 而不是导航 anchor

标签 javascript jquery css

我有以下内容,如果我单击带有 anchor #home#about 等的导航项,它会滚动到下一部分并设置导航元素类到 active 这很棒。

现在我在主页部分的内容中添加了一个“转到关于部分”按钮,该按钮具有 anchor #about。它将我带到该部分,但将 actual button 设置为 active 类,而不是设置 nav item #aboutactive

我的评论在下面 - 只是想知道我该如何解决这个问题。谢谢!

   $(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/

相关文章:

javascript - 检测并修复固定的绝对错误

javascript - 具有垂直滚动和水平页面的表格

css - 简单不编译

html - 为什么菜单元素符号会出现在我的菜单上?

javascript - 如何在 JavaScript 中找到的 div 中获取特定类的元素?

javascript - 关于文字对象语法的限制

javascript - 使用javascript中的if条件比较for循环中的两个字符串

JQuery 函数(窗口调整大小)

jquery - Ratyrate 星星未在生产中加载(heroku)

javascript - 如何使用 jquery sortable 将元素从框 1 拖放到框 2?