向上滚动淡出

时间:2016-10-15 03:09:00

标签: javascript html css

我想在向上滚动时使div淡出。如果你向下看envato.com,当你向下滚动时,有关信息会淡入,然后当你向后滚动时淡出。现在我正在使用下面的js来实现淡入效果,但是我不确定如何让div淡出。

$(function() {
  $(window).scroll( function(){
    $('.fadeInBlock').each( function(i){   
      var bottom_of_object = $(this).position().top + $(this).outerHeight();
      var bottom_of_window = $(window).scrollTop() + $(window).height();

      /* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it  */
      bottom_of_window = bottom_of_window + 350;  

      if ( bottom_of_window > bottom_of_object ) {
        $(this).animate({'opacity':'1'},500);
      }
    }); 
  });
}); 

2 个答案:

答案 0 :(得分:0)

我只是在你的代码中添加一个else语句,将不透明度改回0,这样每次if语句都为false,也就是用户在div出现之后向上滚动它会再次消失,然后重新出现。像这样:

$(function() {
  $(window).scroll( function(){


   $('.fadeInBlock').each( function(i){

    var bottom_of_object = $(this).position().top + $(this).outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();

    /* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it  */
    bottom_of_window = bottom_of_window + 350;  

    if( bottom_of_window > bottom_of_object ){

        $(this).animate({'opacity':'1'},500);

            }
            else{
              $(this).animate({'opacity':'0'},500);
            }
        }); 

    });
}); 

答案 1 :(得分:0)

$(window).on("load",function() {
  $(window).scroll(function() {
    $(".fade").each(function() {
      /* Check the location of each desired element */
      var objectBottom = $(this).offset().top + $(this).outerHeight();
      var windowBottom = $(window).scrollTop() + $(window).innerHeight();

      /* If the element is completely within bounds of the window, fade it in */
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
      } else { //object goes out of view (scrolling up)
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
      }
    });
  }); $(window).scroll(); //invoke scroll-handler on page-load
});
.fade {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div>
  <div class="fade">Fade In 01</div>
  <div class="fade">Fade In 02</div>
  <div class="fade">Fade In 03</div>
  <div class="fade">Fade In 04</div>
  <div class="fade">Fade In 05</div>
  <div class="fade">Fade In 06</div>
  <div class="fade">Fade In 07</div>
  <div class="fade">Fade In 08</div>
  <div class="fade">Fade In 09</div>
  <div class="fade">Fade In 10</div>
</div>

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window