简体   繁体   English

滚动页面时视差在背景图像上滚动

[英]Parallax scroll on background image while scrolling page

I'm stuck on a parallax issue and can't seem to find specifically what I want. 我陷入了视差问题,似乎找不到我想要的东西。

My page has a background image at the top. 我的页面顶部有背景图片。 I have currently got background-position: fixed so it has a parallax effect however I need this image to scroll as the page scrolls? 我目前有background-position: fixed因此具有视差效果,但是我需要此图像在页面滚动时滚动吗? ...And now I'm stuck. ...现在我被困住了。

I believe this can be done with JavaScript and possibly background-position: scroll but I just don't know where to start. 我相信这可以通过JavaScript以及可能的background-position: scroll来完成background-position: scroll但我只是不知道从哪里开始。

In my basic fiddle you can see the parallax effect but I need the image to scroll as the page scrolls. 在我的基本小提琴中,您可以看到视差效果,但是我需要图像随着页面滚动而滚动。

Thanks for any help. 谢谢你的帮助。

 .image { height: 100px; width: 100%; background-repeat: no-repeat; background-size: cover; background-attachment: fixed; background-image: url('http://www.navipedia.net/images/a/a9/Example.jpg'); } 
 <section> <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."</p> </section> <div class="image"></div> <section> <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta."</p> <br><br> <p>"Sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est."</p> </section> 

This function will do the work for you. 此功能将为您完成工作。 (change value of speed variable according to your choice) (根据您的选择改变速度变量的值)

(function(){

  var parallax = document.querySelectorAll(".image"),
      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;

    });
  };

})();

See it in action: https://jsfiddle.net/ksugkmoh/ 实际观看: https : //jsfiddle.net/ksugkmoh/

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

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