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

Parallax scroll on background image while scrolling page

我遇到了视差问题,似乎找不到我想要的具体内容。

我的页面顶部有背景图片。我目前有 background-position: fixed,因此它具有视差效果,但是我需要此图像随着页面滚动而滚动吗? ...现在我卡住了。

我相信这可以用 JavaScript 完成,可能 background-position: scroll 但我不知道从哪里开始。

在我的基本 fiddle 中,您可以看到视差效果,但我需要图像随着页面滚动而滚动。

感谢您的帮助。

.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>

此功能将为您完成工作。 (根据您的选择更改速度变量的值)

(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;

    });
  };

})();

查看实际效果:https://jsfiddle.net/ksugkmoh/