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

后端 未结 8 1090
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    2020-12-12 17:44

    you can use something simple like here: html:

    Motion

    css:

    body {
    
      min-height:4000px;
      background-image: url("http://www.socialgalleryplugin.com/wp-content/uploads/2012/12/social-gallery-example-source-unknown-025.jpg");
    }
    
    h1 {margin-top:300px;}
    

    js:

    (function(){
    
      var parallax = document.querySelectorAll("body"),
          speed = 0.5;
    
      window.onscroll = function(){
        [].slice.call(parallax).forEach(function(el,i){
    
          var windowYOffset = window.pageYOffset,
              elBackgrounPos = "50% " + (windowYOffset * speed) + "px";
    
          el.style.backgroundPosition = elBackgrounPos;
    
        });
      };
    
    })();
    

    Here is jsfiddle

提交回复
热议问题