如何使图像淡出但保持在滚动位置上?

时间:2018-06-30 20:42:19

标签: javascript jquery html css

在Squarespace的Adirondack模板中,有一个钱包的横幅图像,它在您向下滚动时会执行此疯狂的操作,并逐渐淡出为白色,但即使向下滚动时,它似乎也保持在同一位置。很难说清楚我在说什么,所以我包括了我正在谈论的an animated GIF of the image effect。有人对我如何复制它有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您指的是视差滚动,有大量的教程和示例,但这是一个简单的实现

  

https://www.w3schools.com/howto/howto_css_parallax.asp

     

https://codepen.io/nickcil/pen/sfutl

$(window).scroll(function() {
  $(".parallax").css("opacity", 1 - $(window).scrollTop() / 350);
});
.parallax {
  /* The image used */
  background-image: url("https://images.unsplash.com/photo-1530357075171-3c4b84478ebd?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=b930fe4c342d9dcbee9e3b3939ccbe5f&auto=format&fit=crop&w=1300&q=80");
  /* Set a specific height */
  min-height: 500px;
  /* Create the parallax scrolling effect */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Up and Down this page to see the parallax scrolling effect.</p>

<div class="parallax"></div>

<div style="height:1000px;background-color:red;font-size:36px">
  Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
</div>