当某个部分显示在滚动条上时,滚动条出现错误

scroll is wrong while one section is showing on scroll

本文关键字:滚动条 错误 个部 显示      更新时间:2023-09-26

这是我的演示

jQuery(document).ready(function () {
    $('ul.subMenu li a').click(function () {
        jQuery('ul.subMenu li a.curM').removeClass('curM');
        jQuery(this).addClass('curM');
        var target = $(this).attr('href');
        var getHeaderHeight = jQuery(".header_wrap").height();
        $('html, body').stop().animate({
            'scrollTop': $(target).offset().top - getHeaderHeight - (getHeaderHeight*!$(".header_wrap").hasClass("fixed_nav_menu"))
        }, 'fast', 'swing');

    });
    jQuery(window).scroll(function () {
        jQuery('.header_wrap').addClass('fixed_nav_menu');
        if (jQuery(document).scrollTop() == 0) {
            jQuery('.header_wrap').removeClass('fixed_nav_menu');
        }
        jQuery(".hidden_section").fadeIn(1500);
    });
});

演示中名为"第三节"的部分在滚动过程中显示,正因为如此,当你点击它后面的每个部分时,例如"Affiliations",你会看到它现在没有滚动到"Affilinations"部分的相应部分。但是第二次当您单击菜单项"一切正常"时,它会滚动到相应的部分。

我该如何解决这个问题,这样每次当你点击菜单项时,渐变部分都不会阻止滚动相应的部分?

问题在您的方法中:

  • 您试图在导航(例如发布部分(完成后显示(淡入效果(third-sectiondiv,这就是为什么third-section显示在屏幕顶部而不是publication部分

我做了什么:

  • 窗口上的scroll事件是在导航完成后触发的,因此在scroll事件处理程序中添加了在fade-in效果中显示div的逻辑。

  • 将目标元素third-sectionOffset top位置与当前视图端口位置进行检查,基于当滚动或导航时向用户显示third-section具有fade-in效果


JS代码:

 $(window).scroll(function () {
    $('.header_wrap').addClass('fixed_nav_menu');
    if ($(document).scrollTop() === 0) {
        $('.header_wrap').removeClass('fixed_nav_menu');
    }
    var top_of_object = $(".hidden_section").offset().top;
    var bottom_of_window = $(window).scrollTop() + $(window).height();
    /* If the object is completely visible in the window, fade it it */
    if (bottom_of_window > top_of_object) {
        $('.hidden_section').animate({
            'opacity': '1'
        }, 1500);
    }
});

CSS:

.hidden_section {
  /*display:none;*/
  opacity:0
}

注意:不要使用Jquery&$在您的代码中,请在整个代码库中尝试其中一种表示法,否则您的代码看起来太混乱,无法阅读

现场演示@JSFiddle