简体   繁体   English

如何使用jQuery,scrollTop和toggleClass将类添加到主体

[英]How do I add a class to the body using jQuery, scrollTop, and toggleClass

I have a question concerning jQuery's scrollTop functionality, and it's ability to toggle a class based on the amount of vertical scroll. 我对jQuery的scrollTop功能有疑问,它可以根据垂直滚动量切换类。

What I am trying to accomplish is on any page with a "section.banner" class, that after you scroll past the banner a class is applied to the body tag. 我要完成的工作是在带有“ section.banner”类的任何页面上,即在您滚动经过横幅后,将一个类应用于body标签。 This will allow me to change the fill colors of several SVGs that are in the site's header, as well as a fixed positioned side nav that is for pagination. 这将使我能够更改站点标题中的多个SVG的填充颜色,以及用于分页的固定位置的侧面导航。

I am terrible at javascript, and have been stuck searching and trying to get this for hours. 我在javascript方面很糟糕,一直被困在搜索中,并试图花几个小时才能得到它。 any help will be greatly appreciated. 任何帮助将不胜感激。 Here's the code that I'm working with now (CodeKit is telling me it is wrong, which I am not surprised). 这是我现在正在使用的代码(CodeKit告诉我这是错误的,对此我并不感到惊讶)。 The value of 200 is just a placeholder and will be calculated by the height of a fluid image. 值200只是一个占位符,将由流体图像的高度计算得出。 Full disclosure, I have no idea if the brackets and parenthesis are correct. 完全公开,我不知道方括号和括号是否正确。

    // Header/Fixed Pagination Banner Scroll Recoloriing (toggle class)
    // Check If '.banner' Exists
    if( $('section.banner').length > 0) {

        $('body').scrollTop(function)() 
        {
            if $(window).scrollTop >= 200 {
                $('body').toggleClass('downtown');
                return false;
            }
        }
    }

Try something like this : 尝试这样的事情:

if( $('section.banner').length > 0) {

    $(window).scroll(function() {
    {

        if ($(window).scrollTop() >= $('section.banner').scrollTop()) {
            $('body').toggleClass('downtown');
            return false;
        }
    });
}

UPDATE UPDATE

There was little mistake in my code : http://jsfiddle.net/t2yp15hq/ 我的代码几乎没有错误: http : //jsfiddle.net/t2yp15hq/

var top = $('section.banner').position().top;

if($('section.banner').length > 0) {

    $(window).scroll(function() {

        if ($(this).scrollTop() >= top) {
            $('body').addClass('downtown');

        }
        else
        {
            $('body').removeClass('downtown');
        }
    });
}

It does not work with toogleClass, the background is flashing. 它不适用于toogleClass,背景闪烁。

UPDATE UPDATE

http://codepen.io/anon/pen/wBWzXy http://codepen.io/anon/pen/wBWzXy

The solution is to recalculate the top when the window is resized : 解决方法是在调整窗口大小时重新计算顶部:

$(window).resize(function(){
  top = $('section.story-intro').offset().top - 90;
});

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

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