如何让div一次淡出一个

时间:2017-06-21 15:24:58

标签: jquery html css scroll fadeout

我在一个可滚动的包装器中有三个div。我希望每个div在从"包装器#34;,一次滚动时逐渐淡出。

现在我滚动时同时淡出所有三个div。我花了很多时间试图解决这个问题,但仍然无法找到解决方案。

TEST FIDDLE HERE



$(document).ready(function() {
  $(window).scroll(function() {
    $(".title").css("opacity", 1 - $(window).scrollTop() / 300);
  })
});

body {
  margin: 0;
  height: 100%;
}

.wrapper {
  height: 1000px;
  position: relative;
}

.title {
  margin: 0 auto;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
  top: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="title">Image 1</div>
  <br>
  <div class="title">Image 2</div>
  <br>
  <div class="title">Image 3</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

你非常接近,但是你必须遍历这些元素,并将它们的位置分别考虑在页面顶部。

注意:通常听这个滚动事件做这种事情并不是一个好习惯,因为它可能会引发不必要的事情,请尝试阅读:https://www.sitepoint.com/throttle-scroll-events/

注意2:出于性能原因,我在$ titles中缓存了.titles。

$(document).ready(function() {
  var $titles = $(".title");
  $(window).scroll(function() {
    $titles.each(function() {
      $(this).css("opacity", 1 - ($(window).scrollTop() - $(this).position().top )/ 300);
    })
  })
});
body {
  margin: 0;
  height: 100%;
}

.wrapper {
  height: 1000px;
  position: relative;
}

.title {
  margin: 0 auto;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
  top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="title">Image 1</div>
  <br>
  <div class="title">Image 2</div>
  <br>
  <div class="title">Image 3</div>
</div>

答案 1 :(得分:0)

尝试将函数传递给css()而不是值,并相应地处理集合中的索引...但是你必须确定选择器返回的元素的顺序:

&#13;
&#13;
body {
  margin: 0;
  height: 100%;
}

.wrapper {
  height: 1000px;
  position: relative;
}

.title {
  margin: 0 auto;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
  top: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="title">Image 1</div>
  <br>
  <div class="title">Image 2</div>
  <br>
  <div class="title">Image 3</div>
</div>
&#13;
npm -g uninstall serverless  
npm -g install serverless@0.5.6
&#13;
&#13;
&#13;