首页 > 解决方案 > 在滚动顶部闪烁

问题描述

我试图让一段文本在用户向下滚动时消失,并在用户返回顶部时重新出现。它以一种有点初级的、远非顺利的方式取得了成功,但我注意到文本在某个点以一种非常分散注意力的方式闪烁,我不确定问题是什么或如何解决它。

var $win = $(window)
var $doc = $(document)

  $win.scroll(function(e) {
    scrollEffects();
  });

function scrollEffects() {
  var limit = 85;
  var scrolled = $win.scrollTop();
  if ($doc.scrollTop() >= limit) {
    $(".intro").addClass('inactive');
    //$('#banner-contents').css('opacity', 1 - (scrolled * .00280));
    // console.log('scrolled');
  } else {
    $(".intro").removeClass('inactive');
  }
};
body {
  height: 1500px;
  background: tomato;
}

.nav {
  background: white;
  position: sticky;
  top: 0px;
}

.intro {
  color: $black;
  font-size: 1.7rem;
  text-align: center;
}

.inactive {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="nav">
  <p class="intro"> This is some text that should disappear without flickering</p>
  
  Other text
</div>

标签: javascriptjqueryscroll

解决方案


将元素设置为display: none将使文档的布局呈现为好像该元素不是它的一部分。

因此,在您将inactive-class 添加到段落的那一刻,父 nav-div 的高度会发生变化(p.intro可以说是因为消失了)。这当然也会影响滚动位置,现在limit又位于下方。这反过来又删除了inactivep 上的 -class,这会再次更改您的布局......等等。这就是闪烁的原因。

使用visibility代替display

.inactive {
    visibility: hidden;
}

编辑:

如果要逐渐降低段落的高度,可以使用 css 过渡:

.intro {
  color: $black;
  font-size: 1.7rem;
  text-align: center;
  max-height: 2rem; /* or something more appropriate */
  transition: max-height 1s ease;
}

.inactive {
   max-height: 0;
   overflow: hidden;
   transition: max-height 1s ease;
}

或者您可以将段落的高度与滚动位置联系起来:

$('.intro').css('max-height', Math.max(0, 30 - (scrolled * .28)));

当然,在这种情况下,您需要设置max-height: 30px;(或一些适合您需要overflow: hidden;的大小)和intro-class。此外,您将不需要inactive-class。


推荐阅读