如何在我滚动时使图像褪色,可见并且应该重新进行操作

时间:2018-09-21 05:42:23

标签: jquery html css scroll

我正在使用以下js脚本和css来隐藏所有图像的可见性,并且在滚动时它将缓慢显示。它的工作正常,但我的问题是页面加载后其工作一次。如何使图像淡入淡出,不仅在加载页面时出现一次,还必须重复该操作。

function showImages(el) {
  var windowHeight = jQuery(window).height();
  $(el).each(function() {
    var thisPos = $(this).offset().top;

    var topOfWindow = $(window).scrollTop();
    if (topOfWindow + windowHeight - 200 > thisPos) {
      $(this).addClass("fadeIn");
    }
  });
}

$(window).scroll(function() {
  showImages('.star');
});
.star {
  visibility: hidden;
}

.fadeIn {
  -webkit-animation: animat_show 0.8s;
  animation: animat_show 0.8s;
  visibility: visible !important;
}

@-webkit-keyframes animat_show {
  0% {
    opacity: 0
  }
  100% {
    opacity: 1
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg"/>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg">
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg">
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Other  test</p>

1 个答案:

答案 0 :(得分:1)

function showImages(el) {
  var windowHeight = jQuery(window).height();
  $(el).each(function() {
    var thisPos = $(this).offset().top;

    var topOfWindow = $(window).scrollTop();
    if (topOfWindow + windowHeight - 200 > thisPos) {
      $(this).addClass("fadeIn");
    }else{
      $(this).removeClass("fadeIn");
    }
  });
}

$(window).scroll(function() {
  showImages('.star');
});
.star {
  visibility: hidden;
  transition: visibility cubic-bezier(.165, .84, .44, 1) .25s;
}

.fadeIn {
  -webkit-animation: animat_show 0.8s;
  animation: animat_show 0.8s;
  visibility: visible !important;
}

@-webkit-keyframes animat_show {
  0% {
    opacity: 0
  }
  100% {
    opacity: 1
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg"/>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg">
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<img class="star" src="https://www.w3schools.com/html/pic_trulli.jpg">
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Other  test</p>