简体   繁体   English

jQuery滚动功能只能使用一次

[英]jQuery scroll function only works once

I am trying to add a class to the header if the user scrolls past the div #home - and remove the class when you scroll back to the top. 如果用户滚动到div #home则尝试向标题添加一个类,并在滚动回顶部时删除该类。

The issue is, when you scroll past the div it adds the class but when you keep scrolling and then scroll back up, the class does not get removed. 问题是,当您滚动经过div时,它会添加该类,但是当您继续滚动并向上滚动时,不会删除该类。 The event is only firing once... 该活动仅触发一次...

I created this jsFiddle here - https://jsfiddle.net/breezy/9evksr7y/ 我在这里创建了这个jsFiddle- https: //jsfiddle.net/breezy/9evksr7y/

It works in my jsFiddle file but not on my actual web page, I've also tried this... 它可以在我的jsFiddle文件中工作,但不能在我的实际网页上工作,我也尝试过此方法...

$(window).on( 'scroll', function() {

        var header = $('#header'),
            target = $("#home").offset().top;

        var interval = setInterval(function() {
            if ($(window).scrollTop() > 400) {
                // alert("made it!");

                header.addClass('fixed');  

                clearInterval(interval);

            } else {

                header.removeClass('fixed');

            }

        }, 250);


    });

But it still does not work. 但这仍然行不通。 Any idea what I am doing wrong? 知道我在做什么错吗?

Thanks 谢谢


Edit: The issue was that one of my other functions in the same document was conflicting w/ this scroll function. 编辑:问题是我在同一文档中的其他功能之一与此滚动功能冲突。

So I made some minor tweaks to the code. 因此,我对代码做了一些小的调整。 Not sure what the issue was but this seemed to work for me on my webpage. 不知道是什么问题,但这似乎对我的网页有效。

$(window).on('scroll', function() {

  var header = $('#header'),
    target = $("#home").offset().top;

    if ($(window).scrollTop() > target) {

      header.addClass('fixed');

    } else {

      header.removeClass('fixed');

    }

});

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

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