当我滚动到顶部时,无法让我的div淡出OUT

问题描述 投票:1回答:1

我找到了一个脚本来改变滚动的不透明度并稍微修改它。 div退色很好,但是当我回到顶部时,我似乎无法扭转褪色。

当它到达顶部时,我可以让浏览器“警告”我,但不透明度部分没有触发,似乎无法找出原因。

$(document).ready(function() {

  /* Every time the window is scrolled ... */
  $(window).scroll(function() {

    /* Check the location of each desired element */
    $('.hideme').each(function(i) {

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

      /* If the object is completely visible in the window, fade it it */
      if (bottom_of_window > bottom_of_object) {
        $(this).animate({
          'opacity': '1'
        }, 500);
      }

      /*attempt to fade it out*/
      var scrollPosition = $("body, html").scrollTop();
      if (scrollPosition == 0) {
        $(this).animate({
          'opacity': '0'
        }, 500);
      }

    });

  });

});
#container {
  height: 2000px;
}

#container DIV {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
}

.hideme {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

  <div>Hello</div>
  <div class="hideme">Fade In</div>


</div>

JSFiddle

jquery jquery-animate scrolltop
1个回答
1
投票

该代码有几个问题:

  1. bottom_of_window移出each
  2. 没有必要加bottom_of_objectbottom_of_window任何东西,只需要一点offset例如+100bottom_of_window
  3. 而对于fadeOut,只需使用else条件。
  4. 而不是$("body, html").scrollTop();使用$(window).scrollTop()
  5. 当你在这种情况下使用animation时,你最好使用stop()来防止fadeInfadeOut效果之间的冲突。

如有变化,请点击此处:

$(window).scroll(function() {
  var bottom_of_window = $(window).scrollTop() + 100;
  $('.hideme').each(function(i) {
    var bottom_of_object = $(this).offset().top;
    if (bottom_of_window > bottom_of_object) {
      $(this).stop().animate({
        'opacity': '1'
      }, 500);
    } else {
      $(this).stop().animate({
        'opacity': '0'
      }, 500);
    }

  });

});
#container {
  height: 2000px;
}

#container div {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
}

.hideme {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

  <div>Hello</div>
  <div class="hideme">Fade In</div>
  <div class="hideme">Fade In 2</div>
  <div class="hideme">Fade In 3</div>

</div>

你可以使用fadeIn(500)fadeOut(500)而不是$(this).animate({'opacity':'1'},500);

© www.soinside.com 2019 - 2024. All rights reserved.