简体   繁体   English

在滚动和单击时更改活动导航类时出现jquery问题

[英]jquery issues when changing active navigation class on scroll and on click

I'm doing a single page where navigation .active class should change both on scroll and on click. 我正在做一个页面,导航.active类应该在滚动和单击时都改变。 I'm also changing class of header when scrolling down (".large" and ".small"), but this two scripts somehow don't work with each other. 向下滚动(“ .large”和“ .small”)时,我还在更改标头的类,但是这两个脚本在某种程度上无法相互配合。

For header resizing I'm doing this: 对于标题调整大小,我正在这样做:

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

}

}); });

For change active class I'm doing this: 对于更改活动类,我正在这样做:

$(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");
    }
});

} }

This works perfectly when scrolling, but clicking on a top nav link just crashes "header" function and it doesn't resize anymore. 这在滚动时非常有效,但是单击顶部导航链接只会使“标题”功能崩溃,并且不再调整大小。 Can anyone see what's the problem is? 谁能看到问题所在?

As f00bar mentioned, $(document).off("scroll"); 如f00bar所述,$(document).off(“ scroll”); removes the eventhandler. 删除事件处理程序。 The scroll event wont be fired anymore. 滚动事件将不再被触发。 so your top code wont run after a click. 因此,单击后您的最高代码将不会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM