javascript - 在滚动顶部闪烁
问题描述
我试图让一段文本在用户向下滚动时消失,并在用户返回顶部时重新出现。它以一种有点初级的、远非顺利的方式取得了成功,但我注意到文本在某个点以一种非常分散注意力的方式闪烁,我不确定问题是什么或如何解决它。
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
-class 添加到段落的那一刻,父 nav-div 的高度会发生变化(p.intro
可以说是因为消失了)。这当然也会影响滚动位置,现在limit
又位于下方。这反过来又删除了inactive
p 上的 -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。
推荐阅读
- angular - 类型“FormGroup”不可分配给类型“FormControlLike”
- javascript - 在java脚本中连接无限数量的对象
- chef-infra - 在 irb shell 中调试 Ohai 插件
- c# - 生成 RSA 密钥的签名给出错误的数据
- angular - 无法将 POST 请求从 Ionic 应用程序发送到 NestJS 后端
- wordpress - 如何使用 Xpath 过滤掉 Wordpress 插件中的日期字段?
- xml - 以下哪个或哪个陈述在 XML 中是正确的?
- reactjs - 无法在 React 中显示图像,尽管它已导入文件夹中
- typo3 - 带有扩展名“extension_builder”的 TYPO3 错误 ExtensionValidator 不存在。反射失败
- css - 如何在移动浏览器底部放置固定的背景图像*总是*?(CSS)