【问题标题】:jquery issues when changing active navigation class on scroll and on click在滚动和单击时更改活动导航类时出现 jquery 问题
【发布时间】:2014-04-03 08:03:02
【问题描述】:

我正在做一个页面,其中导航 .active 类应该在滚动和点击时都发生变化。向下滚动时,我也在更改标题类(“.large”和“.small”),但这两个脚本不知何故不能相互配合。

为了调整标题大小,我正在这样做:

$(document).on("scroll",function(){
if($(document).scrollTop()>200){
    $('header').removeClass('large').addClass('small');
} else{
    $('header').removeClass('small').addClass('large');

}

});

为了更改活动课程,我正在这样做:

$(document).ready(function () {
$(document).on("scroll", onScroll);

//smoothscroll
$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('a').each(function () {
        $(this).removeClass('active');
    })
    $(this).addClass('active');

    var target = this.hash,
        menu = target;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top+2
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});
});

function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#top-menu a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.
    position().top + refElement.height() > scrollPos) {
        $('#top-menu ul li a').removeClass("active");
        currLink.addClass("active");
    }
    else{
        currLink.removeClass("active");
    }
});

}

这在滚动时非常有效,但是单击顶部导航链接只会使“标题”功能崩溃,并且不再调整大小。谁能看出问题出在哪里?

【问题讨论】:

  • 尝试对文档元素触发 crollTop 动画而不是 'html, body'
  • 不幸的是,这没有帮助

标签: javascript jquery navigation


【解决方案1】:

正如 f00bar 提到的,$(document).off("scroll");删除事件处理程序。滚动事件将不再被触发。所以你的顶级代码在点击后不会运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 2012-12-19
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    相关资源
    最近更新 更多