How do I change my background on scroll using CSS?

前端 未结 1 897
盖世英雄少女心
盖世英雄少女心 2020-12-15 13:33

My website has THE PERFECT FULL PAGE BACKGROUND IMAGE. I grabbed the code for it from css tricks.

If you visit my site you can see it in action.

What I\'d li

相关标签:
1条回答
  • 2020-12-15 14:18

    As others already said, Nop, you can't only with CSS, but a little js code can do it for you.

    Ex.

    jQuery(window).scroll(function(){
        var fromTopPx = 200; // distance to trigger
        var scrolledFromtop = jQuery(window).scrollTop();
        if(scrolledFromtop > fromTopPx){
            jQuery('html').addClass('scrolled');
        }else{
            jQuery('html').removeClass('scrolled');
        }
    });
    

    And in your CSS file:

    html {
        background-repeat: no-repeat;
        background-position: center center;
        background-attachment: fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
    
    html {
        background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg);
    }
    
    html.scrolled {
        background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals_2.jpg);
    }
    

    So basically you are adding or removing a class to the HTML tag at some distance from the top with javascript (jQuery in this case)... and with CSS, changing that image.

    Now on.. you can apply some transitions to the image, or play with the code to made it slideToggle for example instead changing the class.... and many many other options.

    Good luck

    EDIT: Fiddle example: http://jsfiddle.net/pZrCM/

    0 讨论(0)
提交回复
热议问题