(CSS) Make a background image scroll slower than everything else

后端 未结 8 1071
死守一世寂寞
死守一世寂寞 2020-12-12 17:33

here is is my CSS code for the body:

body {
  padding: 0;
  margin: 0;
  background-image: url(\"../images/background.jpg\");
  background-repeat: no-repeat;         


        
相关标签:
8条回答
  • 2020-12-12 17:58

    I know this is very late, but I wondered wether it would not be working easier than the codes above and invested 15 mins of my live.
    Here is my code:

    document.getElementById("body").onscroll = function myFunction() {  
        var scrolltotop = document.scrollingElement.scrollTop;
        var target = document.getElementById("main1");
        var xvalue = "center";
        var factor = 0.5;
        var yvalue = scrolltotop * factor;
        target.style.backgroundPosition = xvalue + " " + yvalue + "px";
      }
    #main1 {
        background-image: url(https://images.unsplash.com/photo-1506104489822-562ca25152fe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9);
        background-position: top center;
        background-attachment:scroll;
        background-size: cover;
        height: 80vh;
        width: 100%;
    }
    #placeholdersoyoucanscroll{
        height:100vh
    }
    <body id="body">
          <main>
            <div id="main1">
            </div>
            <div id="placeholdersoyoucanscroll">
            </div>
        </main>
    </body>

    0 讨论(0)
  • 2020-12-12 17:59

    I also was looking for a modern and intuitive approach to adjusting my background scroll speed. You should try out the Simple Parallax Scrolling jQuery Plug-in, inspired by Spotify.com.

    Once you have it attached to your project, along with a big image to play with, this is one of many ways to set it up.

    The HTML | setup your containers and basic parallax attributes on element.

    <main>
    <section>Some Content Above it</section>
     <div class="parallax-container" data-parallax="scroll" data-position="top" style="height: 80vh;"></div>
    <section>Some Content Below it</section>
    </main>
    

    The jQuery | Here, you can play with additional parameters based on the docs

    function parallaxjs() {
        $('.parallax-container').parallax({
            imageSrc: '/<path-to-your-image>/<your-big-image>.jpg',
            naturalWidth: 1071, //your image width value
            naturalHeight: 500, //your image height value
            bleed: 0,
        });
    }
    
    (function () {
      parallaxjs();
    })($);
    
    0 讨论(0)
提交回复
热议问题