滚动页面停止/空闲时切换类

时间:2016-11-08 07:40:46

标签: javascript jquery css

基本上我有这个代码,如果你向下滚动它隐藏标题菜单然后如果你向上滚动它再次显示标题菜单。

当滚动变为空闲时,我需要隐藏标题菜单,例如我在滚动后空闲3秒后向上滚动页眉菜单显示它隐藏了标题菜单。

$(".slides li").hover(function () {
    $(this).find('.flex-caption').css({opacity: 1.0});
},
function () {
    $(this).find('.flex-caption').css({opacity: 0.0});
});
$('#nav-toggle').on('click', function(e) {
    $(this).toggleClass("active");
    $(".navmobile").slideToggle();
    e.preventDefault();
});
$(document).ready(function(){
    $(window).resize(function() {
        if ($(window).width() >= 1303) {
            $(".navmobile").hide();
            $("#nav-toggle").removeClass("active");
        }
        else {
            $("#nav-toggle").removeClass("active");
            $(".navmobile").hide();
        }
    });
});
        // Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.navbar').outerHeight();
$(window).scroll(function(event){
    didScroll = true;
});
setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 0);
function hasScrolled() {
    var st = $(this).scrollTop();
    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;
    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('.navbar').removeClass('nav-down').addClass('nav-up');
    $("#nav-toggle").removeClass("active");
    $(".navmobile").hide();
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('.navbar').removeClass('nav-up').addClass('nav-down');
}    }
    lastScrollTop = st;
}

1 个答案:

答案 0 :(得分:1)

设置超时3秒即可删除某些课程或执行其他操作:

var timer;

$(window).scroll(function(event){
    didScroll = true;
    clearTimeout(timer);

    timer = setTimeout(function () {
        $('#myHeader').removeClass('idle-scroll');
    }, 3000);
});

此处clearTimeout将停止上一次超时并开始新的超时。