我试图让一段文本在用户向下滚动时消失,并在用户返回顶部时重新出现。它以一种有点基本的、远非顺利的方式取得了成功,但我注意到文本在某个时刻以一种非常分散注意力的方式闪烁,我不确定问题是什么或如何解决它。
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>
最佳答案
将元素设置为 display: none
将使文档的布局呈现为好像该元素不属于文档的一部分。
因此,当您将 inactive
类添加到段落时,父级 nav-div 的高度会发生变化(因为 p.intro
消失了,所以说)。这当然也会影响滚动位置,现在滚动位置再次低于limit
。这反过来会删除 p 上的 inactive
类,从而再次更改您的布局......等等。这就是闪烁的原因。
使用可见性
而不是显示
:
.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: hide;
>介绍inactive
类。
关于javascript - 滚动条顶部闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324619/