background image that moves when you scroll down the page

前端 未结 3 1449
野性不改
野性不改 2021-01-31 23:10

I keep seeing websites with a background image that subtly moves when you scroll down. This is a really nice effect but I\'m not sure how to do this? I\'m am experienced with

相关标签:
3条回答
  • 2021-01-31 23:45

    Like TylerH said, it's called Parallax. You can see an example here.

    Using JavaScript:

    var velocity = 0.5;
    
    function update(){ 
    var pos = $(window).scrollTop(); 
    $('.container').each(function() { 
        var $element = $(this);
        // subtract some from the height b/c of the padding
        var height = $element.height()-18;
        $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) +  'px'); 
       }); 
       };
    
     $(window).bind('scroll', update);
    
    0 讨论(0)
  • 2021-02-01 00:08

    The best library for that is Stellarjs

    Take a look at the example here

    http://markdalgleish.com/projects/stellar.js/demos/backgrounds.html

    0 讨论(0)
  • 2021-02-01 00:09

    Or you could use this simple CSS property which I made a blog post about: http://nathanpeixoto.fr/blog/article8/web-un-one-page-presque-sans-javascript (French only, sorry).

    Let's say this is your HTML:

    <div class="background_container">
    
    </div>
    <style>
    .background_container{
      background-image: url("XXX");
      background-position: center;
      background-size: cover;
      background-repeat: no-repeat;
      background-attachment: fixed; /* <= This one */
    }
    </style>
    
    0 讨论(0)
提交回复
热议问题